[miscellaneous] linux bash shell script usage

기타 유용한 bash 명령어에 대해 작성합니다.

Linux Procedure from log-in to log-out

  1. 로그인 하게 되면 /etc/profile 을 읽는다.
  2. /etc/profile.d/*.sh 를 읽어온다. (profile.d 밑에 *.sh 확장자인 것을 읽어온다.)
  3. 그 다음 ~/.bash_profile (=home directory 밑에 있는 bash_profile) 을 읽어온다. 이것은 각 개인의 마스터 파일이다.
    • ~/.bashrc: 앞에 . 이 하나 붙는데 이 뜻은 .bashrc 파일을 읽어오라는 의미이다. (= C 언어의 include 와 같다.)
  4. bashrc 을 읽어온다. 이것은 보조 파일이다.
  5. /etc/bashrc 을 읽어온다. 모든 사용자에게 적용되며 $PS1 변수가 들어있다.
  6. bash_history : 로그아웃했을 때 이전 실행했던 명령어들을 이 파일에 저장하고 빠져 나온다.
  7. bash_logout : 로그아웃을 했을 때 어떤 일을 하고 싶으면 여기다가 적으면 된다.

if-statement

if [ 조건문 ]; then
	실행문
elif [ 조건문 ]; then
	실행문
fi

if 문을 살펴보면 [ ] 안은 조건문이고 -f 는 파일의 존재 여부를 묻는다고 생각하면 된다. 즉 home directory 밑에 .bashrc 파일이 존재하는지를 묻고 있고 참이면 아래 문장을 실행한다.

# example)
if [ "$CONDITION_VALUE" == "foo" ]; then
	echo "condition is foo"
elif [ "$CONDITION_VALUE" == "bar" ] then
	echo "condition is bar"
fi
  • alias: 축약어를 의미한다.
    alias gb='gedit ~/.bashrc'
    alias sb='source ~/.bashrc'
    
  • export 는 지역 변수를 전역변수화 시키는 것이다.
    export CONDITION_VALUE="foo"
    

Example: if-statement

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
# Ask for user input
read -p "Do you want to proceed Anaconda? (y/yes): " user_input

# Check if the input is 'y' or 'yes'
if [[ $user_input == "y" || $user_input == "yes" ]]; then
    # Place the commands you want to execute here
    echo "Enable Conda Environements"
	__conda_setup="$('/home/rilab/anaconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
	if [ $? -eq 0 ]; then
	    eval "$__conda_setup"
	else
	    if [ -f "/home/rilab/anaconda3/etc/profile.d/conda.sh" ]; then
	        . "/home/rilab/anaconda3/etc/profile.d/conda.sh"
	    else
	        export PATH="/home/rilab/anaconda3/bin:$PATH"
	    fi
	fi
	unset __conda_setup
fi
# <<< conda initialize <<<

realworld 실험을 할 때에 ROS와 Anaonda의 호환 문제가 잦은 편이다. 그래서 대체로는 pyenv를 통해 python 가상환경을 정리해주고 있지만, 기타 github repo에서는 conda 환경을 추천하는 경우도 흔히 있다. 그렇기에, 나는 매번 터미널을 켜줄 때마다 Conda Enable에 대해 물어보도록 하는 조건문을 ~/.bashrc 에 추가하였다.




Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • [miscellaneous] tmux usage
  • [miscellaneous] pyenv usage
  • [miscellaneous] docker usage
  • [구현] AprilTag Pose Estimation
  • [study] Vector Quantization