리눅스/Bash Script

[Bash Script] Branching(exit, test, if-then-fi, case)

jetblack1 2023. 11. 8. 08:46

1. exit 

  • 실행된 프로그램이 종료된 상태를 전달
  • 0         프로그램 또는 명령이 성공으로 종료했음을 의미
  • 1-255   프로그램 또는 명령이 실패로 종료했음을 의미
  •      1           일반에러
  •      2           Syntax error
  •      126       명령을 실행할 수 없음
  •      127       명령(파일)이 존재하지 않음
  •      128+N  종료 시그널+N(kill -9 PID 로 종료 시 128+9=137)
    • $?  종료 값 출력

  • Ex)
    •  $ cp file1 : file1 파일이 없어서 error 발생
    •  $ echo $? 일반에러 이므로 1 출력

 

2. test

  • 비교연산자
  • test <명령어> or [명령어]
  • 명령어 실행결과를 true(0) 또는 false(1)로 리턴 한다.
    • test 명령어는 다양한 연산자를 지원한다.
    • x -eq y : x=y true
    • x -gt y : x > y true
    • x -ge : x >= y true
    • x -lt y : x < y true
    • x -le y : x <= y true
    • x -ne y : x 와 y 값이 같지 않으면 true

  • Ex)
    • x=10
    • test $x -lt 5
    • echo $? 를 통해 결과 확인
    • 위의 test 대신 [ $x -lt 5 ] 로도 표현 가능하다. 

    • -e file : 파일이 존재하면 true
    • -d file : 파일이 디렉토리이면 true
    • -f file : 파일이 file이면 true
    • -x file : 파일이 실행가능하면 true
  • Ex)
test -e /etc/passwd
test -f /tmp

 

 

3. if-then-fi

  • 조건 명령어. command 실행 결과에 따라 서로 다른 comand를 실행
if <command>
then
 <command>
fi

 

Ex)

x=10
if test $x -gt 5
then
  echo "x is greater than 5"
fi
  • 해당 명령 수행 시 x는 5보다 크기 때문에 참이므로 then 에 해당하는 문구가 실행 된다.
    x를 4로 할 경우 then에 있는 문구는 건너 띄고 fi로 이동하여 해당 if문이 끝난다

 

  • else를 추가하여 해당 명령이 거짓일 경우 else로 이동하여 명령을 수행하게 할 수 있다. 
if <command>

then

 <command1>

else

 <command2>

fi

 

  • Ex)
if test -e /etc/passwd
then
ls -l /etc/passwd
else
echo "/etc/passwd file does not exsit!"
fi
  • 해당 명령을 수행하면 /etc/passwd 있을경우 then 에 있는 ls -l /etc/passwd 실행.
  • 없으면 else에 있는 command를 실행한다.

 

  • 파일명을 입력 받아서 결과를 출력하는 스크립트
#!/bin/bash
echo -n "filename?"
read filename
if [ -e $filename ]
then
 ls -l /etc/passwd
else
 echo "/etc/passwd file does not exsit!"
fi

 

 

4. case

  • 입력받은 값에 따라서 명령어를 실행.
case "$variable" in

 pattern1) command1;;

 pattern2) command2;;

 *) command3 ;;

esac

 

  • Ex)
#!/bin/bash
echo -n "What do you want?"
read answer
case $answer in
 yes) echo "System restart.";;
 no) echo "shutdown the system";;
 *) echo "entered incorrectly";;
esac
  • yes,no,나머지 명령을 입력할 경우 각 부분의 값이 출력된다
  • yes 입력 시 대,소문자를 구분하므로 대,소문자 둘다 사용하고 싶다면 [yY] 으로 설정 한다.

 [yY]es) echo "System restart.";;
 [Nn]o) echo "shutdown the system";;
 *) echo "entered incorrectly";;