logo

조건문 | 쉘 스크립트

조건문: Bash 프로그래밍에 사용할 수 있는 조건문은 총 5개입니다.

  1. if 문
  2. if-else 문
  3. if..elif..else..fi 문(Else If 래더)
  4. if..then..else..if..then..fi..fi..(중첩 if)
  5. 스위치 문

구문에 대한 설명은 다음과 같습니다.

if 문
이 블록은 지정된 조건이 true인 경우 처리됩니다.
통사론:



if [ expression ] then statement fi>

if-else 문
if 부분에서 지정된 조건이 true가 아닌 경우 else 부분이 실행됩니다.
통사론

if [ expression ] then statement1 else statement2 fi>

if..elif..else..fi 문(Else If 래더)
하나의 if-else 블록에서 여러 조건을 사용하려면 셸에서 elif 키워드를 사용합니다. 표현식1이 참이면 명령문 1과 2를 실행하고 이 프로세스가 계속됩니다. 조건 중 어느 것도 참이 아니면 다른 부분을 처리합니다.
통사론

if [ expression1 ] then statement1 statement2 . . elif [ expression2 ] then statement3 statement4 . . else statement5 fi>

if..then..else..if..then..fi..fi..(중첩 if)
중첩된 if-else 블록은 한 조건이 만족된 다음 다른 조건을 다시 확인하는 경우 사용할 수 있습니다. 구문에서 표현식1이 false이면 else 부분을 처리하고 다시 표현식2를 확인합니다.
통사론:

if [ expression1 ] then statement1 statement2 . else if [ expression2 ] then statement3 . fi fi>

스위치 문
Case 문은 지정된 값이 패턴과 일치하면 스위치 문으로 작동하며 특정 패턴의 블록을 실행합니다.
일치하는 항목이 발견되면 이중 세미콜론(;;)이 실행될 때까지 연관된 모든 문이 실행됩니다.
마지막 명령이 실행되면 케이스가 종료됩니다.
일치하는 항목이 없으면 케이스의 종료 상태는 0입니다.

통사론:

case in Pattern 1) Statement 1;; Pattern n) Statement n;; esac>

예제 프로그램

예시 1:
구현if>성명




#Initializing two variables> a=10> b=20> > #Check whether they are equal> if> [>$a> ==>$b> ]> then> >echo> 'a is equal to b'> fi> > #Check whether they are not equal> if> [>$a> !=>$b> ]> then> >echo> 'a is not equal to b'> fi>

>

>

산출

$bash -f main.sh a is not equal to b>

예시 2:
구현if.else>성명




#Initializing two variables> a=20> b=20> > if> [>$a> ==>$b> ]> then> >#If they are equal then>print> this> >echo> 'a is equal to b'> else> >#>else> print> this> >echo> 'a is not equal to b'> fi>

>

>

산출

$bash -f main.sh a is equal to b>

예시 3:
구현switch>성명




CARS=>'bmw'> > #Pass the variable in string> case> '$CARS'> in> >#>case> 1> >'mercedes'>)>echo> 'Headquarters - Affalterbach, Germany'> ;;> > >#>case> 2> >'audi'>)>echo> 'Headquarters - Ingolstadt, Germany'> ;;> > >#>case> 3> >'bmw'>)>echo> 'Headquarters - Chennai, Tamil Nadu, India'> ;;> esac>

>

>

산출

$bash -f main.sh Headquarters - Chennai, Tamil Nadu, India.>

메모: 쉘 스크립팅은 대소문자를 구분하는 언어입니다. 즉, 스크립트를 작성하는 동안 올바른 구문을 따라야 합니다.

아푸르바 파가온카르