개발/Linux

bash shell branching (조건문)

달리초이 2023. 1. 2. 15:09


[목차]

1. exit

2. test

3. if-then-fi

4. case


1. exit

- 실행된 프로그램이 종료된 상태를 전달

exit <숫자>
0 프로그램 또는 명령이 성공으올 종료했음을 의미
1-255 프로그램 또는 명령이 실패로 종료했음을 의미 (
1 일반 에러
2 Syntax Error
126 명령을 실행할 수 없음
127 명령 (파일) 이 존재하지 않음
128+N 종료 시그널+N (kill -9 PID 로 종료 시 128+9=137)

$? 종료 값 출력

cp file1
echo $?
# 1

sleep 100
<Ctrl><c>
echo $?
# 130 			: 128 + 2(KILL:SIGINT)
kill -l

 

 

 

2. test

- 비교연산자

test <명령어> or [ 명령어 ]

- 명령어 실행결과를 true(0) 또는 false(1)로 리턴한다.

- test 명령어는 다양한 연산자를 지원한다.

연산자 설명
x -eq y x값과 y값이 같으면 true 리턴
x -gt y x값이 y값보다 크면 true 리턴
x -ge y x값이 y값보다 크거다 같으면 true 리턴
x -lt y x값이 y값보다 작으면 true 리턴
x -le y x값이 y값보다 작거나 같으면 true 리턴
x -ne x값과 y값이 같지 않으면 true 리턴
-e file 파일이 존재하면 true 리턴
-d file 파일이 디렉토리이면 true 리턴
-f file 파일이 파일이면 true 리턴
-x file 파일이 실행할 수 있으면 true 리턴
x=10
test $x -lt 5
echo $?
# 1

test $x -gt 5
echo $?
# 0

test -e /etc/passwd
test -f /tmp

[ $x -lt 5 ]
[ $x -gt 5 ]
[ -e /etc/passwd ]
[ -f /tmp ]

- 기본 산술 연산 명령어: let과 expr

let 5+5
let sum=5+5
echo $sum
# 10

let multi=5*5
echo $multi
# 25

 

 

 

3. if-then-fi

- 조건 명령어. command 실행 결과에 따라 서로 다른 command를 실행

@따배셸

cat > if-exam.sh
#!/bin/bash
echo -n "input number: "
read x
if [ $x -gt 5 ]
then
	echo "x is greater than 5"
fi

chmod +x if-exam.sh

@따배셸

cat > if-exam2.sh
#!/bin/bash
echo -n "input filename: "
read filename
if [ -e $filename ]
then
	ls -l $filename
else
	echo "$filename file does not exsit"
fi

chmod +x if-exam2.sh

 

 

 

4. case

- $var의 값에 따라 선택해서 명령어를 실행

case "$variable" in
	pattern1) command1 ;;
    pattern2) command2 ;;
    *) command3 ;;
esac

- 예시

echo -n "What do you want? "
read answer
case $answer in
    yes) echo "System restart.";;
    no) echo "shutdown the system";;
    *) echo "entered incorrectly";;
esac
# << 기호는 뒤에 END가 나올 때까지 한 번에 입력 받아서 한 번에 출력함

vi case-exam.sh

#!/bin/bash
#: Usage	: case-exam.sh
cat << END
=============================
Please select a number.
-----------------------------
1: Check disk usage
2: Check the login user list
-----------------------------
END
echo -n "number: "
read number
case $number in
    1) df -h ;;
    2) who ;;
    *) echo "Bad choice!"
	exit 1 ;;
esac
exit 0

# 실행 권한 추가
chmod +x case-exam.sh

 

 

- 문제풀이 : shell script 작성하기

1) 대화식으로 사용자에게 디렉토리 이름을 입력 받음

2) 입력한 디렉토리 이름이 실제 디렉토리이면 해당 디렉토리 모든 파일 목록을 /tmp/날짜.txt 파일에 저장하고, 디렉토리가 아니면 "It's not a directory." 메시지를 출력하고 종료하는 shell script를 작성하시오.

cat > lab4.sh
#!/bin/bash
echo -n "Input a directory name: "
read dirname
if [ -e $dirname ]
then ls $dirname > /tmp/$(date +%Y%m%d).txt
else echo "It's not a directory"; exit 1
fi

chmod +x lab4.sh

 

 

 

 

- 출처 : 따배셸

8. Branching

https://youtu.be/hG9T3K00qiE

728x90
반응형