Coding/Shell script

Shell script 조건문

dodomp0114 2021. 11. 2. 00:14

● if 문

 

if ~ then 문

if command
then
	commands
fi

 

if ~ else 문

if command
then
	commands
else
	commands
fi

 

if ~ elif 문

if command1
then
	commands
elif command2
then
	commands
elif command3
then
	commands
elif command4
then
	commands
fi

 

 


 

● 비교문

 

 

- 숫자열 비교문

비교문 설명
n1 -eq n2 n1과 n2가 같은지 검사한다.
n1 -ge n2 n1과 n2보다 크거나 같은지 검사한다.
n1 -gr n2 n1과 n2보다 큰지 검사한다..
n1 -le n2 n1과 n2보다 작거나 같은지 검사한다.
n1 -lt n2 n1과 n2보다 작은지 검사한다.
n1 -ne n2 n1과 n2가 같지 않은지 검사한다.

 

ex)

#!/bin/bash

value1=10
value2=11

if [ $value1 -gt 5 ]
then
	echo "The test value $value1 is greater than 5"
fi

 

- 문자열 비교문

비교문 설명
str1 = str2 str1이 str2와 같은지 검사한다.
str1 != str2 str1이 str2와 같지 않은지 검사한다.
str1 < str2 str1이 st2보다 작은지 검사한다.
str1 > str2 str1이 st2보다 큰지 검사한다.
-n str1 str1의 길이가 0보다 큰지 검사한다.
-z str1 str1의 길이가 0인지 검사한다.

 

ex)

#!/bin/bash
val1=baseball
val2=hockey

if [ $val1 \> $val2 ]
then
	echo "$val1 is greater than $var2"
else
	echo "$val1 is less than $val2"
fi

 


- 파일 비교문

비교문 설명
-d file 파일이 존재하고 디렉토리인지 검사
-e file 파일이 존재하는지 검사
-f file 파일이 존재하고 파일인지 검사
-r file 파일이 존재하고 읽을 수 있는지 검사
-s file 파일이 존재하고 비어 있지 않은지 검사
-w file 파일이 존재하고 기록할 수 있는지 검사
-x file 파일이 존재하고 실행할 수 있는지 검사
-O file 파일이 존재하고 현재 사용자가
소유한 것인지 검사
-G file 파일이 존재하고 기본 그룹이 현재 사용자와 같은지 검사
file1 -nt file2
file1이 file2보다 새것인지 검사
file1 -ot file2 file1이 file2보다 오래된 것인지 검사

 

ex)

#!/bin/bash

my_directory=/root

if [ -d $my_directory ]
then
	echo "The $my_directory directory exists"
else
	echo "The $my_directory directory does not exist"
fi

 


 

● case 문

 

case var in
pattern1 | pattern2) commands1;;
pattern3) commands2;;
*) default commands;;
esac

ex)

#!/bin/bash

case $USER in
rich | barbara)
	echo "Welcome, $USER"
    echo "Please enjoy your visit";;
testing)
	echo "Special testing account";;
jessica)
	echo "Do not forget to log off when you're done";;
*)
	echo "Sorry, you are not allowed here";;
esac

 

 

● for 문 

 

for var in list
do
	commands
done

ex)

#!/bin/bash

for test in Seoul Busan Incheon 
do
	echo The next state is $test
done

 

 

 

C 스타일 for 문

for (( variable assignment; condition; iteration process ))

ex)

#!/bin/bash
for (( a=1, b=10; a <= 10; a++, b-- ))
do
	echo "$b - $a"
done

 

 

 

 

● while 문

-  조건문이 참 일때 루프,

    조건문이 거짓 일때 탈출.

while test command
do
	other commands
doone

ex)

#!/bin/bash

var1=10
while [ $var1 -gt 0 ]
do 
	echo $var1
    var1=$[ $var1 - 1 ]
done

 

 

 

● until 문

-  조건문이 거짓 일때 루프,

    조건문이 참 일때 탈출.

until test commands
do
	other commands
done

ex)

#!/bin/bash

var1=100

until [ $var1 -eq 0 ]
do
	echo $var1
    var1=$[ $var1 - 25 ]
done