Programming/Bash
[Bash] Export Variable
신샤인
2022. 1. 22. 18:05
반응형
Export Variable
스크립트를 돌릴 때 export를 사용해야 출력된다.
기본적으로 Command Line에서 지정했을 경우 로그아웃 후 재접속 시 해당 변수는 초기화 되어 있다.
그래서 .bashrc 파일에 해당 변수를 지정한다.
Linux 내 모든 계정에 적용하고 싶다면 /etc/profile에 입력한다.
.bashrc와 /etc/profile에 같은 변수가 지정되어 있다면? .bashrc 변수를 가져온다.
[root@scriptbox scripts]# cat 7.testvar.sh
#!/bin/bash
echo "The $SEASON season is logner"
[root@scriptbox scripts]# chmod +x 7.testvar.sh
#명령어로 출력하면 바로 나오지만 스크립트는 export를 이용해야 출력됨
[root@scriptbox scripts]# SEASON="winter"
[root@scriptbox scripts]# echo $SEASON
winter
[root@scriptbox scripts]# ./7.testvar.sh
The season is logner
[root@scriptbox scripts]# export SEASON
[root@scriptbox scripts]# ./7.testvar.sh
The winter season is logner
#로그아웃하고 다시 스크립트 실행 시 해당 변수는 초기화 되어 있음
#bashrc에 설정
[root@scriptbox ~]# source .bashrc
[root@scriptbox ~]# cat .bashrc
# .bashrc
# User specific aliases and functions
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
# Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
export SEASON="Winter"
#변수가 없지만 다시 Root로 로그인하고 확인 시 해당 변수가 설정되어 있음.
[root@scriptbox ~]# echo $SEASON
[root@scriptbox ~]# exit
logout
[vagrant@localhost ~]$ sudo -i
[root@scriptbox ~]# echo $SEASON
Winter
#Global 변수를 설정하고 싶을 땐 /etc/profile 설정
vim /etc/profile
...
export SEASON="Summmer"
...
# .bashrc vs /etc/profile
# 글로벌 설정은 /etc/profile이지만 .bashrc에 설정이 되어 있다면 먼저 가져온다.
[vagrant@scriptbox ~]$ echo $SEASON
Summer
[vagrant@scriptbox ~]$ sudo -i
[root@scriptbox ~]# echo $SEASON
Winter
반응형