처리를 하다 보면 조건에 따라 처리를 다르게 하고 싶은 경우가 있습니다.
쉘 스크립트에서도 if문을 사용해 조건식을 지정할 수 있습니다.
if문 기본 사용방법은 아래와 같습니다.
if(20세 이상일 경우) 성년입니다. else //20세 이상이 아닐 경우 미성년입니다. fiif 뒤에 조건식을 작성합니다.
else는 if문에 해당하지 않는 조건일 경우에 실행을 하게 됩니다.
fi는 if문의 종료를 의미합니다.
if 문 사용법쉘 스크립트 내에서 if문을 어떻게 사용하는지 알아보겠습니다.
먼저 조건이 하나일 경우에 사용하는 방법입니다.
if [ 조건1 ]; then 처리1 fi조건1에 값이 만족하는 경우에 처리1을 실행하게 됩니다.
만약 조건1에 만족하지 않는 경우에는 처리1을 실행하지 않습니다.
조건1에 만족하지 않는 경우 다른 처리를 하고 싶은 경우 else를 사용합니다.
if [ 조건1 ]; then 처리1 else 처리2 fi조건1에 만족하는 경우에는 처리1을 만족하지 않는 경우에는 처리2를 실행합니다.
조건을 여러 개 작성하고 싶은 경우에는 elif를 사용해 조건식을 늘릴 수 있습니다.
if [ 조건1 ]; then 처리1 elif [ 조건2 ]; then 처리2 else 처리3 fi샘플을 만들어 확인해보겠습니다.
#!/bin/sh num=10 if [ "${num}" -eq 2 ]; then echo "num is 2" elif [ "${num}" -eq 3 ]; then echo "num is 3" else echo "num is not 2 or 3" fiif 조건식에는 비교 연산자를 사용해 값을 비교할 수 있습니다.
비교 연산자 | 의미 | 비교 연산자 | 의미 |
-eq | 같음 | < | 이중 소괄호에서, 더 작음 |
-ne | 같지 않음 | <= | 이중 소괄호에서, 작거나 같음 |
-gt | 더 큼 | > | 이중 소괄호에서, 더 큼 |
-ge | 크거나 같음 | >= | 이중 소괄호에서, 크거나 같음 |
-lt | 더 작음 | ==, = | 문자열 비교, 같음 |
-le | 더 작거나 같음 | != | 문자열 비교, 같지 않음 |
-z | 문자열이 null인가 | -a | 논리 and |
-n | 문자열이 null이 아님 | -o | 논리 or |
다른 프로그래밍 언어에서도 마찬가지이지만 쉘 스크립트에서도 if 문은 상당히 중요합니다.
조건식을 사용방법을 알고 있으면 더욱더 많은 처리를 응용해 사용할 수 있기 때문입니다.
여러 조건을 넣어 보면서 사용해보면 금세 익힐 수 있습니다.
쉘스크립트(shell script)로도 If elif 를 사용할 수 있습니다.
가끔 쓰기 때문에 기억이 잘 나지 않아서 말이지요.
그리고 case 구문을 지원하기 때문에 여러 조건을 확인해야 하는 것도 가능하지만
case문은 가독성이 너무 떨어지기 때문에 거의 사용하지 않습니다.
어쨌든 shell script (bash 기준)에서 if, elif, else 구문은 이렇게 씁니다.
Shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #!/bin/bash a="1" if[[$a=="1"]];then echo"a is 1" elif[[ $a=="2"]];then echo"a is 2" elif[[$a=="3"]];then echo"a is 3" elif[[$a=="4"]];then echo"a is 4" else echo "a is not 1, 2, 3, or 4" fi |
Post Views: 640
---------------------------------------------------------
# if 기본 구문
---------------------------------------------------------
if [ Condition ]
then
< Statement >
fi
# 조건문
# AND
if [ ${string1} == ${string2} ] && [ ${string3} == ${string4} ]
..생략
# OR
if [ ${string1} == ${string2} ] || [ ${string3} == ${string4} ]
..생략
# 다중 조건
if [[ ${string1} == ${string2} || ${string3} == ${string4} ]] && [ ${string5} == ${string6} ]
..생략
---------------------------------------------------------
# Simple Bash if/else statement
---------------------------------------------------------
#!/bin/bash
printf "Enter a number: "
read number
if [ $number -lt 100 ]; then
"echo “Your entered number is less than 100"
fi
# output
$ bashif.sh
Enter a number:10
“Your enterednumberislessthan100”
$ bashif.sh
Enter anumber:100
---------------------------------------------------------
# Simple Bash if/else statement
---------------------------------------------------------
#!/bin/bash
directory="./BashScripting"
# bash check if directory exists
if [ -d $directory ]; then
echo "Directory exists"
else
echo "Directory does not exists"
fi
# output
$ bashtest.sh
Directory doesnotexists
---------------------------------------------------------
# if-elif-else
---------------------------------------------------------
#!/bin/bash/
printf "Enter a number from 1-20: "
read number
if [ $number -lt 10 ]; then
echo "Your entered number is less than 10"
elif [ $number -le 20 ]; then
echo "Your entered number is greater than 10"
else
echo "You entered number is not between 1-20"
fi
# output
$ test.sh
Enter anumberfrom1-20:4
Your enterednumberisless than10
$ bashtest.sh
Enter anumberfrom1-20:14
Your enterednumberisgreaterthan10
$ bashtest.sh
Enter anumberfrom1-20:30
You enterednumberisnotbetween1-20
---------------------------------------------------------
# Nested if/else
---------------------------------------------------------
#!/bin/bash
choice=4
# Print to stdout
echo "1. Bash"
echo "2. Scripting"
echo "3. Tutorial"
echo -n"Please choose a word [1,2 or 3]? "
# Loop while the variable choice is equal 4
# bash while loop
while [ $choice -eq 4 ]; do
# read user input
read choice
# bash nested if/else
if [ $choice -eq 1 ]; then
echo "You have chosen word: Bash"
else
if [ $choice -eq 2 ]; then
echo "You have chosen word: Scripting"
else
if [ $choice -eq 3 ]; then
echo "You have chosen word: Tutorial"
else
echo "Please make a choice between 1-3 !"
echo "1. Bash"
echo "2. Scripting"
echo "3. Tutorial"
echo -n"Please choose a word [1,2 or 3]? "
choice=4
fi
fi
fi
done
# output1
$ bashtest.sh
1. Bash
2. Scripting
3. Tutorial
Please chooseaword [1,2 or 3]? 1
You have chosenword:Bash
# output2
$ bashtest.sh
1. Bash
2. Scripting
3. Tutorial
Please chooseaword [1,2 or 3]? 2
You havechosenword:Scripting
# output3
$ bashtest.sh
1. Bash
2. Scripting
3. Tutorial
Please choose aword [1,2 or 3]? 3
You havechosenword:Tutorial
---------------------------------------------------------
# OR 조건 (||)
---------------------------------------------------------
#!/bin/bash/
printf "Enter a number: "
read number
if [ $number -le 10 ] || [ $number -le 20 ]; then
echo "You have entered the correct number"
else
echo "Your entered the incorrect number"
fi
# output
$ bashtest.sh
Enter anumber:5
You haveenteredthecorrectnumber
$ bashtest.sh
Enter a number:13
You haveenteredthecorrectnumber
$ bashtest.sh
Enter anumber:70
Your enteredthe incorrectnumber
---------------------------------------------------------
# Mathematical Operators
---------------------------------------------------------
#!/bin/bash
if [ $1 -gt 0 ]; then
echo "$1 > 0"
fi
if [ $1 -ge 0 ]; then
echo "$1 >= 0"
fi
if [ $1 -eq 0 ]; then
echo "$1 == 0"
fi
if [ $1 -ne 0 ]; then
echo "$1 != 0"
fi
if [ $1 -lt 0 ]; then
echo "$1 < 0"
fi
if [ $1 -le 0 ]; then
echo "$1 <= 0"
fi
# output
$ bashtest.sh-3
-3 != 0
-3 < 0
-3 <= 0
$ bashtest.sh5
5 > 0
5 >= 0
5 != 0
$ bashtest.sh0
0 >= 0
0 == 0
0 <= 0
---------------------------------------------------------
# String Operators
---------------------------------------------------------
#!/bin/bash
string_null=""
string1="string1"
if [ $string_null -n ]; then
echo "not null string"
else
echo "null string"
fi
if [ $string_null -z ]; then
echo "null string"
else
echo "not null string"
fi
if [ "$string_null" == "$string1" ]; then
echo "strings equal"
else
echo "strings not equal"
fi
if [ "$string_null" != "$string1" ]; then
echo "strings not equal"
else
echo "strings equal"
fi
# output
$ basttest.sh
not nullstring
null string
strings notequal
strings notequal
---------------------------------------------------------
# Test for files and directories
---------------------------------------------------------
#!/bin/bash
if [ -s $1 ]; then
echo "$1 not empty file"
fi
if [ -f $1 ]; then
echo "$1 normal file. Not a directory"
fi
if [ -e $1 ]; then
echo "$1 exists"
fi
if [ -d $1 ]; then
echo "$1 is directory and not a file"
fi
if [ -r $1 ]; then
echo "$1 is read-only file"
fi
if [ -x $1 ]; then
echo "$1 is executable"
fi
# output
$ bashtest.shtest.sh
test.sh notemptyfile
test.sh normalfile.Notadirectory
test.sh exists
---------------------------------------------------------
# if…else…fi
---------------------------------------------------------
#!/bin/sh
if [ $# -eq 0 ]; then
echo "$0 : You must give/supply one integers"
exit 1
fi
if [ $1 -gt 0 ]; then
echo "$1 number is positive"
else
echo "$1 number is negative"
fi
# output
$ bashtest.sh
test.sh : Youmustgive/supplyoneintegers
$ bashtest.sh1
1 number is positive
$ bashtest.sh-1
-1 numberisnegative
$ bashtest.sh100100100
100 number is positive
---------------------------------------------------------
# 참고사이트
---------------------------------------------------------
//devhints.io/bash
//programmingexamples.wikidot.com/bash-scripting
//blog.gaerae.com/2015/01/bash-hello-world.html