프로그래밍/Unix

쉘 스크립트(Shell Script) 제어문 - if 문

미냐님 2020. 5. 9. 21:56
728x90

if 문

  • 주어진 조건을 만족할 때만 명령을 실행

if ~ then ~ else 문

  • if 다음에 주어진 조건 명령을 실행하여 종료값이 0이면
    • then 다음의 명령을 실행
    • 0이 아니면 else 다음의 명령을 실행
  • 조건 명령에 연산식이 올 경우
    • 계산 결과 값이 0이면 종료값은 1
    • 계산 결과 값이 0이 아니면 종료값은 0
  • else문은 생략할 수 있음
  • 형식
if 조건 명령
then
    명령
[ else
    명령 ]
fi
  • 스크립트의 예
$ cat –n test_if
1 #!/bin/bash
2 #
3 # if test
4 #
5
6     echo “Input x :”
7 read x
8     echo “Inpt y :”
9 read y
10
11 if (( x<y ))
12 then
13    echo “$x is less than $y.”
14 else
15    echo “$y is less than $x.”
16 fi
$
  • 실행 결과
$ chmod +x test_if
$ ./test_if
Input x :
100
Input y :
200
100 is less than 200.
$

if ~ then ~ elif ~ else 문

  • elif문은 조건 명령1이 실패일 때(종료 값이 0 아닌 값) 새로운 분기 명령을 실행
if 조건명령1
then
    명령
elif 조건명령2
then
    명령
else
    명령
fi
  • 스크립트의 예
$ cat –n test_elif
1 #!/bin/bash
2 #
3 # elif test
4 #
5
6     echo “Input Score :”
7 read score
8
9 if (( $score >= 90 ))
10 then
11    echo “Your score is great.”
12 elif (( $score >= 80 ))
13 then
14    echo “Your score is good.”
15 else
16    echo “Your score is not good.”
17 fi
$
  • 실행 결과
$ chmod +x test_elif
$ ./test_elif
Input Score :
50
Your score is not good.
$

 

조건 테스트

  • if 문에 사용되는 조건은 수치 연산자 외에도 문자열의 비교, 파일에 관련된 비교, 확인 작업을 수행할 수 있음
  • 배시 쉘은 문자열을 비교하는 연산자와 다양한 파일 테스트 플래그 제공

  • 스크립트의 예
$ cat -n test_string
1 #!/bin/bash
2 #
3 # test string
4 #
5
6     echo “Are you OK (y/n) : ”
7 read ans
8
9 if [[ $ans = [Yy]* ]]
10 then
11    echo “Happy to hear it.”
12 else
13    echo “That’s to bad.”
14 fi
$
  • 실행 결과
$ chmod +x test_string
$ ./test_string
Are you OK (y/n) :
y
Happy to hear it.
$
  • 문자열 비교 패턴에 다양한 정규 표현식 사용할 수 있음

  • 스크립트의 예 : 입력한 파일의 종류 알려주는 스크립트
$ cat -n test_file
1 #!/bin/bash
2 #
3 # test file type
4 #
5 echo “Input file name : ”
6 read file
7
8 if [[ ! -e $file ]]
9 then
10 echo “$file File not exists.”
11 elif [[ -f $file ]]
12 then
13 echo “$file is a regular file.”
14 elif [[ -d $file ]]
15 then
16 echo “$file is a directory.”
17 else
18 echo “$file is a special file.”
19 fi
$
  • 실행 결과
$ chmod +x test_file
$ ./test_file
Input file name :
aa
aa File not exists.
$ ./test_file
Input file name :
test_if
test_if is a regular file.
$ ./test_file
Input file name :
/dev/null
/dev/null is a special file.
$
728x90