Bash Script If statement

Bash 스크립트 if 조건문 문법

기본적으로, if / elif / else / fi 로 구성한다. 

if[] bracket 사이에는 공백이 있어야 하며, [] bracket 과 [[ ]] double bracket( ) paranthesis 는 다를 수 있으므로 주의하자.

if [ expression ]

then

statement

elif [ expression ]

then

statement

else 

statement

fi


expression 에 사용하는 Comparison 은 아래와 같다.

integer comparison

if [ "$a" -eq "$b" ]  : 같음(equal to)

if [ "$a" -ne "$b" ]  : 다름(not equal to)

if [ "$a" -lt "$b" ]  : 작음(less than)

if (( "$a" < "$b" ))

if [ "$a" -gt "$b" ] : 큼(greater than)

if (( "$a" > "$b" ))

if [ "$a" -le "$b" ] : 작거나 같음(less than or equal to)

if (( "$a" <= "$b" ))

if [ "$a" -ge "$b" ] : 크거나 같음(greater than or equal to)

if (( "$a" >= "$b" ))


string comparison

if [ "$a" == "$b" ]  : 같음(equal to)

if [ "$a" = "$b" ] ※ = 양쪽 모두 빈 칸 이여야 함

if [ "$a" != "$b" ]  : 다름(not equal to)

if [ -z "$a" ] : string 이 null 이 아님(즉, 0이 아닌 길이가 있는 string)


if statement 에 not 을 사용하고자 하는 경우 ! 를 사용하면 된다.

if ! [ "$arg" -eq "matching" ]

then

echo "Not matched with the first one"

fi


If statement 를 사용해 file 존재 유무 확인

if [ -d <DIR> ] : Directory 가 존재

if [ -f <FILE> ] : 파일이 존재하며, directory 가 아님

if [ -x <FILE> ] : 파일이 실행 가능함

if [ -f test.c ]

then

echo "File test.c exists!"

else

echo "File test.c does not exist"

fi


If statement  Logical AND, OR 문법

if [[ condition1 && condition2 ]] : Logical AND

if [ condition1 ] && [ condition2 ]

if [ condition1 -a condition2 ]

if [[ condition1 || condition2 ]] : Logical OR

if [ condition1 ] || [ condition2 ]

if [ condition1 -o condition2 ]

if [[ condition1 && condition2 ]] || [[ condition3 && condition4 ]]

then

echo "Condition (1 AND 2) OR (3 AND 4)"

fi



참조

http://tldp.org/LDP/abs/html/comparison-ops.html

'Programming > Bash Script' 카테고리의 다른 글

Bash Script Variable Split by Space  (0) 2018.02.04
Bash Script Echo  (0) 2018.02.04
Bash Script String  (0) 2017.07.04
Bash script argument  (0) 2017.06.20
Bash script sudo 권한 체크  (1) 2017.06.19

예측은 적중할 수도, 빗나갈 수도 있다.

다만, 예측 없이 진행하는 것은 눈을 감고 앞으로 가는 것과 같다.

'Life > A sentense of the day' 카테고리의 다른 글

작가의 숨은 의도  (0) 2017.07.09
포장의 기술  (0) 2017.07.07
  (0) 2017.07.03
선택과 집중  (0) 2017.07.03
영원함  (0) 2017.07.01

누구에게나 꿈은 있다.

꿈을 향해 나아가는 것은 힘든 일 일 수 있지만,

꿈을 향해 나아가고 있다는 자체가 행복한 것 일 수 있다.


'Life > A sentense of the day' 카테고리의 다른 글

포장의 기술  (0) 2017.07.07
예측  (0) 2017.07.04
선택과 집중  (0) 2017.07.03
영원함  (0) 2017.07.01
우선 순위  (0) 2017.07.01

+ Recent posts