VBScript 조건문

조건문

VBScript에는 4개의 조건문이 있음.

  • if 문
  • if then else 문
  • if then elseif 문
  • select case 문

... 생략

if .. the .. elseif

  i = hour( time )
  response.write( "i : " & i & "<br/>" )

  if i = 8 then
    response.write( "Just started..!" )
  elseif i = 11 then
    response.write( "Hungry" )
  elseif i = 12 then
    response.write( "Lunch-time!" )
  elseif i = 17 then
    response.write( "Time to go home!" )
  else
    response.write( "Holy SHIT!" )
  end if

select case

switch 문과 같음.

  <% @CODEPAGE="65001" language="vbscript" %>
  <% Response.CharSet = "utf-8" %>
  <!DOCTYPE html>
  <html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
    <%
      d = weekday( data )

      response.write( "weekday( data ) : " & d & "<br/>" )

      select case d
        case 1
          response.write( "SUNDAY 아이스크림 먹고싶다" )
        case 2
          response.write( "MONDAY 출근 안 했으면 좋겠다" )
        case 3
          response.write( "TUESDAY 죽을 것 같다" )
        case 4
          response.write( "WEDNESDAY 점심이 길어서 그나마 참는다" )
        case 5
          response.write( "THURSDAY 피곤해 죽을 것 같다" )
        case 6
          response.write( "FRIDAY 주말 생각해서 참는다" )
        case else
          response.write( "SATURDAY 방전이다" )
      end select
    %>
  </body>
  </html>

728x90
반응형

'WEB > ASP' 카테고리의 다른 글

[ASP] form  (0) 2021.08.26
[ASP] 반복문  (0) 2021.08.26
[ASP] Procedure  (0) 2021.08.26
[ASP] 변수  (0) 2021.08.26
[ASP] 문법  (0) 2021.08.25

선택 제어문과 반복 제어문

프로그램 언어의 제어구조 파악.
선택제어문과 반복제어문 그리고 프로그램을 통해 제어구조 파악.

  • 학습 목표

    1. 프로그램 제어구조를 이해할 수 있음.
    2. 선택제어문의 종류와 그 기능 이해.
    3. 반복제어문의 종류와 그 기능 이해.
    4. 기타제어문의 기능 이해.

프로그램 언어의 제어 구조

  • 순차적 제어 : 특별한 지정이 없는 한, 위에서 아래로 수행되는 제어구조.
  • 선택적 제어 : 주저징 조건에 따라 특정 부분으로 수행을 옮기는 분기 제어 구조.
  • 반복적 제어 : 특정 부분을 일정한 횟수만큼 반복 수행하는 반복 제어 구조.

선택 제어문

선택 제어문의 종류

단순 제어 if

  • 주어진 조건에 따라 명령문을 수행한다.

  • 형식

    1.  if( 조건 )
         명령문 1;
         명령문 2;
    2.  if( 조건 ) {
         명령문 1;
         ...
         명령문 n;
       }
       ...
  • 단순 if 문의 조건에 따른 분기
    05-01.png

  • 단순 if문의 사용 예

#include <stdio.h>

int main()
{
  int a = 10, b = 20;

  if (a > b)
  {
    a = a + 20;
    printf("a = %d\n", a);
  }

  b = b + 20;
  printf("b = %d\n", b);

  return 0;
}

if-else

  • 주어진 조건에 따라 다른 명령문을 수행한다.

  • 형식

    •   if( 조건 )
          명령1;
        else
          명령2;
  • 단순 if 문의 조건에 따른 분기
    05-02.png

  • if-else 문의 사용 예

    #include <stdio.h>
    #pragma warnig(disable : 4996)
    int main()
    {
    int a, b, max;
    
    printf("\ninsert a >> ");
    scanf("%d", &a);
    printf("\ninsert b >> ");
    scanf("%d", &b);
    
    if (a >= b)
      max = a;
    else
      max = b;
    
    printf("max = %d\n", max);
    
    return max;
    }

다중 if - else 문

  • 주어진 조건 1과 2에 따라 수행하는 명령이 다르다.

  • 형식

    •   if( 조건1 )
          if( 조건2 )
            명령문1;
          else
            명령문2;
        else
          명령문3;
  • 다중 if - else 문의 조건에 따른 분기
    05-03.png

  • 다중 if - else 문의 예

    •   #include <stdio.h>
        #pragma warnig(disable : 4996)
        int main()
        {
          int a;
          printf("\ninsert a number : ");
          scanf("%d", &a);
      
          if (a >= 0)
            if (a == 0)
              printf("ZERO\n");
            else
              printf("OVER ZERO\n");
          else
            printf("UNDER ZERO\n");
      
          return 0;
        }

다중 if - else if - else

  • 형식

      if( 조건1 )
        명령1;
      else if( 조건2 )
        명령2;
      else if( 조건3)
        멸령3;
      else
        명령4;
  • 다중 if-else if-else 문의 조건에 따른 분기
    05-04.png

  • 다중 if - else if - else if - else 문의 예

    •   #include <stdio.h>
        #pragma warning(disable : 4996)
      
        int main()
        {
          int score = 0;
          printf("\n성적 입력 : ");
          scanf("%d", &score);
      
          if (score >= 90)
            printf("A\n");
      
          else if (score >= 80)
            printf("B\n");
      
          else if (score >= 70)
            printf("C\n");
      
          else if (score >= 60)
            printf("D\n");
      
          else
            printf("F\n");
      
          return 0;
        }

switch - case

  • 주어진 값에 따라 여러 곳 중 한 곳으로 분기하여 실행

  • 형식 :

      switch( 수식 ) {
        case 값1 : 명령어1;
        case 값2 : 명령어2;
        ...
        default : 명령어;
      }
  • switch - case 문의 처리 순서도
    05-05.png

  • swtich - case 문의 사용 예 (break 미사용)

      #include <stdio.h>
      #pragma warning(disable : 4996)
      int main() {
        int n;
    
        printf("\ninsert a number : ");
        scanf("%d", &n);
    
        printf("\n n %% 5 = %d\n", n % 5);
    
        switch (n % 5) {
          case 0: printf("remainder : 0\n");
          case 1: printf("remainder : 1\n");
          case 2: printf("remainder : 2\n");
          default: printf("remainder : 3 or etc..\n");
        }
    
        return 0;
      }
  • swtich - case 문의 사용 예 (break 사용)

      #include <stdio.h>
      #pragma warning(disable : 4996)
      int main() {
        int n;
    
        printf("\ninsert a number : ");
        scanf("%d", &n);
    
        printf("\n n %% 5 = %d\n", n % 5);
    
        switch (n % 5) {
          case 0: printf("remainder : 0\n");
            break;
          case 1: printf("remainder : 1\n");
            break;
          case 2: printf("remainder : 2\n");
            break;
          default: printf("remainder : 3 or etc..\n");
        }
    
        return 0;
      }

goto

무조건 적인 분기문

  • 기능 : 프로그램 수행 도중에 원하는 곳으로 제어를 무조건적으로 옮긴다.

  • 형식

      Label :
    
      goto Label
  • goto 사용 예

      #include <stdio.h>
      #pragma warning(disable : 4996)
      int main()
      {
        int i, n, c = 'A';
    
        while (1)
        {
    
          printf("\n num : ");
          scanf("%d", &n);
    
          for (i = 1; i <= n; i++)
          {
            printf("%c", c);
    
            if (c == 'Z')
              goto end;
            else if (c == 'Q')
              goto findQ;
    
            c++;
          }
        }
    
      end:
        printf("\n>> FIN <<\n");
    
      findQ:
        printf("\n>> I FIND F!! <<\n");
    
        return 0;
      }
  • goto 문이 사용 될 수 없는 경우

    • label의 위치가 특정 함수(if, for) 안에 있을 경우

반복 제어문

for

  • 기능 : 주어진 조건이 만족되는 동안 루프문을 반복 수행한다.

  • 형식

      for( 초기식; 조건식; 증감식 ) {
        반복 실행될 문장;
      }
  • for 문의 처리 순서
    05-06.png

  • 사용 예

      #include <stdio.h>
    
      int main()
      {
        int i, sum = 0;
    
        for (i = 0; i <= 10; i++)
          sum = sum + i;
    
        printf("SUM OF from 1 to %d = %d\n", i - 1, sum);
    
        return 0;
      }

다중 for 문

  • 기능 : 주어진 조건이 만족되는 동안 푸르문을 반복 수행한다.

  • 형식

      for( 초기식; 조건식; 증감식 ){
        for( 초기식; 조건식; 증감식 ){
          for( 초기식; 조건식; 증감식 ){
            // 반복 실행될 문장
          }
        }
      }
  • ex

      #include <stdio.h>
    
      int main()
      {
        int a, b;
    
        for (a = 1; a <= 3; ++a)
        {
          printf("a = %d\n", a);
          for (b = 0; b <= 4; b++)
            printf("\tb = %d", b);
          putchar('\n');
        }
    
        return 0;
      }

while

  • 기능 : 주어진 조건이 만족되는 동안 반복문을 수행

  • 형식 :

      while( 조건식 ) {
        // 반복 수행괼 문장;
      }
  • 처리 순서
    05-07.png

  • 사용 예

      #include <stdio.h>
    
      int main()
      {
        int i = 0, sum = 0;
    
        while (i <= 100)
        {
          sum = sum + i;
          i++;
        }
    
        printf("SUM OF FROM 1 TO 100 = %d\n", sum);
        return 0;
      }
  • 다중 while 예

      #include <stdio.h>
    
      int main()
      {
    
        int i = 2, j;
    
        while (i < 10)
        {
          j = 1;
          while (j < 10)
          {
            printf("%d x %d = %d \n", i, j, i * j);
            j++;
          }
          printf("\n");
          i++;
        }
    
        return 0;
      }

do - while

  • 기능 : 반복문 내의 명령을 실행한 후, 주어진 조건을 검사, 반복 여부를 결정함.

  • 형식 :

      do {
        반복_수행_문장;
      } while( 조건식 );
  • do - while의 처리 순서
    05-08.png

  • ex )

      #include <stdio.h>
      #pragma warning(disable : 4996)
    
      int main()
      {
        int i = 0, sum = 0, n;
    
        printf("\n>> insert n : ");
        scanf("%d", &n);
    
        do
        {
          sum = sum + i;
          i++;
        } while (i <= n);
    
        printf("i = %d\n", i);
        printf("SUM OF FROM i TO %d : %d\n", n, sum);
        return 0;
      }

기타 제어문

break

  • for, while, do - while, switch 블록등을 강제적으로 벗어날 때 사용.

  • 자신이 포함된 반복문만 빠져 나온다.

  • 사용 예

      #include <stdio.h>
      #pragma warning(disable : 4996)
    
      int main()
      {
    
        int num, sum = 0;
    
        while (1)
        {
          printf("insert num (end:0): ");
          scanf("%d", &num);
    
          if (num == 0)
            break;
    
          sum = sum + num;
        }
    
        printf("\nsum = %d\n", sum);
        return 0;
      }

continue

  • 반복문 중에 다음 반복문을 실행하고자 할 때 사용.

  •   #include <stdio.h>
      #include <math.h>
      #pragma warning(disable : 4996)
    
      int main()
      {
        int num = 1;
    
        while (num != 0)
        {
          printf("\n num : ");
          scanf("%d", &num);
    
          if (num < 0)
          {
            printf("0 : Negative Number!\n");
            continue;
          }
    
          printf("Square root of %d = %f\n", num, sqrt(num));
        }
    
        printf("\n>> BYE <<\n");
        return 0;
      }
728x90
반응형

'Language > C' 카테고리의 다른 글

[C] 함수와 기억 클래스 - 2  (0) 2020.12.25
[C] 함수와 기억 클래스 - 1  (0) 2020.12.20
[C] 입출력 함수와 연산자 - 2  (0) 2020.12.20
[C] 입출력 함수와 연산자 - 1  (0) 2020.12.15
[C] 자료형과 선행 처리기  (0) 2020.12.14

유지보수나 기능 개선프로젝트를 진행하면서 분기 처리 부분에서 가독성이 떨어지는 코드를 많이 보게 되었다.
종종 이런 코드는 가독성이 떨어지는건 물론이고 코드 작성자 본인도 가독성 문제로 오류를 만들어 내는 로직도 있었다.

 


연산자 우선 순위

좋은 분기분을 만들기 전에 언어별 연산자 우선순위를 알아야 한다.
결합 방법에 대해서는 언어별, 버전별 기준으로 정확하지 않으니 참고만 하면 된다.
언어별 연산자 우선순위는 사칙 연산에서 곱셈/나눗셈이 덧셈/뺄셈보다 먼저 이뤄지는 것처럼 이해하면 된다.

 


java 연산자 우선순위

우선순위 연산 기호 결합 방향
1 [], . >>>>
2 x++, x-- <<<<
3 ++x, --x,_x, -x, ~, !, (type) <<<<
4 *, /, % >>>>
5 +, - >>>>
6 <<, >>, >>> >>>>
7 <, >, <=, >=, instanceof >>>>
8 ==, != >>>>
9 & >>>>
10 ^ >>>>
11   >>>>
12 && >>>>
13    
14 ? a : b <<<<
15 =, +=, -=, *=, /=, %=, &=, ^=, !=, <<=, >>=, >>>= <<<<

 

javascript 연산자 우선순위

자바스크립트 연산자 우선순위(비트 연산자 제외)
순위 기능 연산자
1 괄호 ()          
2 증감/논리 연산자 not ++ -- !      
3 산술 연산자 곱셈 * / %      
4 산술 연산자 덧셈 + -        
5 비교 연산자 대소 < <= > >=    
6 비교 연산자 같음 == === != !==    
7 논리 연산자 and &&          
8 논리 연산자 or ||          
9 대입 연산자 = += -= *= /= %=

 

python 연산자 우선순위

우선순위 연산자 설명
1 (값...), [값...], {키: 값...}, {값...} 튜플, 리스트, 딕셔너리, 세트 생성
2 x[인덱스], x[인덱스:인덱스], x(인수...), x.속성 리스트(튜플) 첨자, 슬라이싱, 함수 호출, 속성 참조
3 await x await 표현식
4 ** 거듭제곱
5 +x, -x, ~x 단항 덧셈(양의 부호), 단항 뺄셈(음의 부호), 비트 NOT
6 *, @, /, //, % 곱셈, 행렬 곱셈, 나눗셈, 버림 나눗셈, 나머지
7 +, - 덧셈, 뺄셈
8 <<, >> 비트 시프트
9 & 비트 AND
10 ^ 비트 XOR
11    
12 in, not in, is, is not, <, <=, >, >=, !=, == 포함 연산자, 객체 비교 연산자, 비교 연산자
13 not x 논리 NOT
14 and 논리 AND
15 or 논리 OR
16 if else 조건부 표현식
17 lambda 람다 표현식

 


단축 평가 (Short-circuit Evaluation)

단축 평가는 and(&&) 연산자와 or(||) 연산자의 원리를 이해하면 쉽다.

    if( condition1 && condition2 && condition3 && condition3 )

위와 같이 && 연산자로 여러 boolean 값의 상황이 있을 때, && 연산자는 하나의 조건이라도 false면 결과가 false 이기 때문에,
condition1이 false라면 굳이 뒤에 있는 2, 3, 4를 확인하지 않는다.

    if( condition1 || condition2 || condition3 || condition3 )

마찬 가지로 || 연산자로 여러 boolean 값의 상황이 있을 때는 condition1이 true면 그다음 조건은 검사하지 않는다.
이런 단축 평가의 개념으로 boolean 값이 간단하게 나오는 상황을 앞 쪽에 적용하면 빠르게 처리할 수 있다.

 


가독성 높은 분기 처리 방법

중첩 if

일반적으로 개발할 시 긍정적(유효한) 상황을 염두하고 개발을 하는데,
지속적으로 유효성을 체크하는 로직이 들어갈 경우 if 문이 계층구조처럼 구성이 만들어지기도 함.

    Object getUserInfo() {
      Session session = getSession();
      if( session != null ) {
        User user = session.getAttribute("loginUser");
        if( user != null ) {
          String id = user.getId();
          if( id != null ) {
            // 처리할 로직
          }
        }
      }
    }

 

중첩 if - 개선

역으로 부정적(유효하지 않는) 상황을 염두하고 분기 처리를 하면, 가독성과 구조적으로 좋은 코드가 나옴.
실제 처리할 로직이 시작하기 전에 유효하지 않는 상황으로 분기되면 해당 메소드나 함수를 return이나 예외 처리로 벗어나는 것을 보호절 숙어 라고 함.

    Object getUserInfo() {
      Session session = getSession();
      if( session == null ) return;

      User user = session.getAttribute("loginUser");
      if( user == null ) return;

      String id = user.getId();
      if( id == null ) return;

      // 처리할 로직
    }

 

 


loop 내에서의 분기 처리

    String line;
    while( line = reader.readline() ) {
      if( line.startsWith('#') || line.isEmpty() )
        continue;

      //  처리할 로직
    }

 

 


가독성을 위한 if

좌변에 유동적인 값이나 표현을 넣고, 우변에 상수와 같은 고정 값을 넣어야 가독성이 좋아짐.

    if( 10 <= length )

    //  아래가 더 보기 편함.
    if( length >= 10 )

 

 


if/else 블록의 순서

  • 가능하다면 if 조건 안에는 긍정 조건을 넣어야 가독성이 좋음.
  • 단, if/else 처리 로직 중 간단한 로직을 먼저 if 절에 넣는 것이 가독성이 좋음.
  • 단, 보호절 숙어가 우선순위가 높음. 부정의 조건을 넣어서 계층 구조를 만들지 않을 수 있다면 이게 더 낫다는 의미.
  •   if( hasAuth ) {
        // 간단하고 긍정적인 내용
      } else {
        // 상대적으로 복잡하고 긴 내용
      }

 


삼항 연산자

  • 간단한 구문일 경우 : 삼항 연산자.
  • 복잡한 구문일 경우 : if/else.

삼항 연산자는 코드 한 줄로 가독성을 챙길 수 있으며, 한 줄로 처리하기 복잡할 경우에는 if/else를 사용하는 게 낫다.

  • 삼항 연산자가 이득인 경우
  • let timeType = hour < 12 ? 'am' : 'pm';
  • if/else가 이득인 경우
  •   let timeKor, timeEng;
      if( hour < 12 ) { 
          timeKor = '오전';
        timeEng = 'am';
      } else { 
          timeKor = '오후';
        timeEng = 'pm';
      }

 


복잡한 분기 추출

재사용되거나, 분기 절 내의 복잡한 내용을 메소드로 표현하게 되면 더 나은 가독성을 얻을 수 있다.

  • 기존
  •     if( user.id == post.registerId ) {
            // 사용자가 게시물의 작성자 이다.
        } else {
            // 사용자가 게시물의 작성자가 아니다.
        }
  • 개선
  •     boolean isEditable = isOwner( user, post );
        if( isEditable ) {
            // 사용자가 게시물의 작성자 이다.
        } else {
            // 사용자가 게시물의 작성자가 아니다.
        }
        boolean isOwner( User user, Post post ) { return user.id == post.registerId; }

 


드모르간 법칙

괄호 중첩이 적을수록 가독성이 좋다.

  • 기존
  • if( !(hasfile && !isPrivate) ) return false;
  • 개선
  • if( !hasFile || isPrivate ) return false;

 


복잡한 논리 가독성 향상

한 라인으로 논리를 표현하지 않고, 가독성을 위해 적절한 여러 라인으로 분리하여 보호절과 유사하게 한다.

  • 기존
  •   public class Range {
        private int bgn;
        private int end;
        // this의 bgn이나 end가 other의 bgn이나 end에 속하는지 확인
        private boolean isOverlapsWith( Range other ) {
          return ( this.bgn >= other.bgn && this.bgn < other.end )
              || ( this.end > other.bgn && this.end <= other.end )
              || ( this.bgn <= other.bgn && this.end >= other.end );
        } 
      }
  • 개선
  •   public class Range {
        private int bgn;
        private int end;
        // this의 bgn이나 end가 other의 bgn이나 end에 속하는지 확인
        private boolean isOverlapsWith( Range other ) {
          // this가 시작하기 전에 끝난다.
          if( other.end <= this.bgn ) return false;
          // this가 끝난 후에 시작한다.
          if( other.bgn >= this.end ) return false;
          // 겹친다.
          return true;
        }
      }

 


switch 문의 사용

if-else 문은 각 조건문을 iterate 하며 로직을 결정한다. N개의 if-else 구문이 있다면 N번의 조건 여부를 판단한다.
switch 문은 입력받은 케이스로 로직이 바로 넘어가게 된다.
일반적으로 4개 이상의 조건일 때 if-else 보다 switch 문을 사용하는 것이 성능에 좋다고 한다.

시간 복잡도

다음은 if-else와 switch의 시간 복잡도이다.

  • if-else : O(N)
  • switch : O(logN)
  int num = 5;
  int ret;

  if (num == 0)      ret = num;
  else if (num == 1) ret = num;
  else if (num == 3) ret = num;
  else if (num == 5) ret = num;
  else if (num == 7) ret = num;
  else               ret = num;

  System.out.println(ret);
  int num = 5;
  int ret;

  switch (num) {
    case 0: ret = num; break;
    case 1: ret = num; break;
    case 3: ret = num; break;
    case 5: ret = num; break;
    case 7: ret = num; break;
    default: ret = num; break;
  }
  System.out.println(ret);

 

 


참고자료 :

728x90
반응형

쉘 스크립트 - 2

  • 학습 개요
    쉘 스크립트에서 선택과 반복을 위한 제어 구조를 사용해보자.
    선택 구조인 if / case, 반복 주조인 for / while / until 명령의 문법과 의미를 알아 보자.
    조건 검사가 필요할 때 사용되는 명령과 수식의 작성법을 알아 보자.

  • 학습 목표

    1. 선택 구조를 사용하여 쉘 스크립트를 작성하자.
    2. 반복 구조를 사용하여 쉘 스크립트를 작성하자.
    3. 수식을 포함하는 쉘 명령을 선택과 반복 구조에서 사용하자.

선택 구조

제어 구조

  • 쉘 스크립트에서 실행을 제어하기 위해 선택과 반복 구조를 사용함.
  • if, for, case, while, until

if

  • 프로그래밍 언어에서 if 문의 기능

if command ...; then
  command ...
[ elif command; then
  command ... ]...
[ else
  command ... ]
fi
  • ;은 같은 라인에서 다른 단어(then elif else fi)와 구분이 필요할 때 사용함.
  • if다음의 명령을 실행하여 참이면 then 다음의 명령을 실행함. (if 명령은 종료됨)
    • if나 elif 다음에 조건 검사를 위한 test 명령을 사용할 수 있음.
    • if나 elif 다음에 나오는 마지막 명령의 종료 상탯값으로 참과 거짓을 구분함.
    • 종료 상탯값 0은 성공적 종료를 의미하며 참으로 간주.
  • 거짓이면 elif 다음의 명령을 실행하여 참 / 거짓을 판단하고 실행함.
  • 만족 되는 것이 없으면 else 다음의 명령을 실행함.
  [ec2-user@ip-AWS ~]$ cd /usr/bin
  [ec2-user@ip-AWS bin]$ echo $?
  0
  [ec2-user@ip-AWS bin]$ cd /bin/usr
  -bash: cd: /bin/usr: No such file or directory
  [ec2-user@ip-AWS bin]$ echo $?
  1
  [ec2-user@ip-AWS bin]$ if true; then
  > echo "SUCCESS"
  > else
  > echo "FAILURE"
  > fi
  SUCCESS
  [ec2-user@ip-AWS bin]$ if true; false; then
  > echo "TRUE"
  > fi

test

  • 조건 검사를 위해 사용하는 명령
  • 조건이 만족되면 종료 상탯값으로 0(true), 1(false)를 리턴함
  • test expression || [ expression ]
    • expression은 파일의 상태 검사, 문자열의 비교, 정수 비교를 위한 수식
    • **대괄호와 expression 사이에 공백이 있어야 함.
[ec2-user@ip-AWS ~]$ cat intCompare.sh
#! /bin/bash
if [ $# !=2 ]; then
        echo "you must supply two numbers as arguments"
        exit 1
fi

if [ $1 -eq $2 ]; then
        echo "$1 equals to $2"
elif [ $1 -gt $2 ]; then
        echo "$1 is greater than $2."
else
        echo "$1 is less than $2."
fi

echo "$1 + $2는 $[$1+$2]임."

[ec2-user@ip-AWS ~]$ chmod u+x intCompare.sh

[ec2-user@ip-AWS ~]$ ./intCompare.sh 36 68
./intCompare.sh: line 2: [: 2: unary operator expected
36 is less than 68.
36 + 68는 104임.

case

  • 다중 선택을 지원하는 복합 명령
    • switch 문과 비슷
case word in
  [ pattern [ | pattern ]... ) command...;; ]...
esac
  • word 부분을 먼저 확장하고 pattern과 매칭되는지 검사함
  • 매칭이 이루어지면 상응하는 명령이 수행됨
  • 일단 매칭이 이루어지면 이후의 매칭 시도는 없음
  • pattern에서 *은 프로그래밍에서 'default 키워드'를 사용함.

case에서 패턴 사용 예

pattern ) desc (word가 다음과 같은 경우 패턴 매칭이 일어남)
a) a인 경우
[[:alpha:]]) 1개의 알파벳 문자인 경우
???) 임의의 세 글자인 경우
*.txt .txt로 끝나는 경우
[aeiou]) 모음에 해당하는 영문 소문자 1개인 경우
[ABE][0-9] 앞 글자가 A, B, E중 하나이고 다음 글자가 숫자인 두 글자인 경우
*) 임의 길이의 글자와 매칭됨. case 명령에서 마지막 패턴으로 사용하는 것이 좋음

case 실행의 예

[ec2-user@ip-AWS ~]$ cat caseTest.sh
#!/bin/bash

echo "
plz select :
a. Display System Information
b. Show Information about File Systems
c. Summarlize Disk Usage Information
q. Quit
"

read -p "Enter selection [a, b, c or q] > "

case $REPLY in
  a|A)
      echo "Hostname : $HOSTNAME"
      uptime
      ;;
  b|B)
      df -h
      ;;
  c|C)
      if [$( id -u) -eq 0 ]; then
        echo "All user's home disk space utillization"
        du -sh /home/*
      else
        echo "($USER)' home disk space utilization"
        du -sh $HOME
      fi
      ;;
  q|Q)
      echo "Program terminated."
      exit
      ;;
  *)
      echo "Invalid entry" > $2
      exit 1
      ;;
esac

[ec2-user@ip-AWS ~]$ ./caseTest.sh
plz select :
a. Display System Information
b. Show Information about File Systems
c. Summarlize Disk Usage Information
q. Quit

Enter selection [a, b, c or q] > a
Hostname : ip-AWS.ap-northeast-2.compute.internal
07:45:43 up 34 days, 0 min,  1 user,  load average: 0.00, 0.00, 0.00


[ec2-user@ip-AWS ~]$ ./caseTest.sh
plz select :
a. Display System Information
b. Show Information about File Systems
c. Summarlize Disk Usage Information
q. Quit

Enter selection [a, b, c or q] > b
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        474M     0  474M   0% /dev
tmpfs           492M     0  492M   0% /dev/shm
tmpfs           492M  408K  492M   1% /run
tmpfs           492M     0  492M   0% /sys/fs/cgroup
/dev/xvda1      8.0G  1.9G  6.2G  24% /
tmpfs            99M     0   99M   0% /run/user/1000

[ec2-user@ip-AWS ~]$ ./caseTest.sh
plz select :
a. Display System Information
b. Show Information about File Systems
c. Summarlize Disk Usage Information
q. Quit

Enter selection [a, b, c or q] > c
./caseTest.sh: line 19: [1000: command not found
(ec2-user) home disk space utilization
92K     /home/ec2-user

[ec2-user@ip-AWS ~]$ ./caseTest.sh
plz select :
a. Display System Information
b. Show Information about File Systems
c. Summarlize Disk Usage Information
q. Quit

Enter selection [a, b, c or q] > d
./caseTest.sh: line 30: $2: ambiguous redirect

[ec2-user@ip-AWS ~]$ ./caseTest.sh
plz select :
a. Display System Information
b. Show Information about File Systems
c. Summarlize Disk Usage Information
q. Quit

Enter selection [a, b, c or q] > g
./caseTest.sh: line 30: $2: ambiguous redirect

[ec2-user@ip-AWS ~]$ ./caseTest.sh
plz select :
a. Display System Information
b. Show Information about File Systems
c. Summarlize Disk Usage Information
q. Quit

Enter selection [a, b, c or q] > q
Program terminated.

반복 구조

for

  • 모든 데이터를 한 차례씩 처리하는 제어구조
  •   for variable [ in word ... ]; do
        command ...
      done
  • word ... 부분 (값의 목록)을 먼저 확장함
  • word 목록에 존재하는 값을 순차적으로 변수 variable에 대입하고 do와 done 사이의 명령을 수행함.
  • word 부분이 없다면 in "$@"가 있는 것으로 가정함.
  [ec2-user@ip-AWS ~]$ echo {A..D}
  A B C D
  [ec2-user@ip-AWS ~]$ for i in {A..D}; do echo $i; done
  A
  B
  C
  D
  [ec2-user@ip-AWS ~]$ cat testFor.sh
  #! /bin/bash
  for FILE
  do
    echo $FILE
  done

  [ec2-user@ip-AWS ~]$ chmod u+x testFor.sh

  [ec2-user@ip-AWS ~]$ ./testFor.sh `ls`
  arg.sh
  caseTest.sh
  first.sh
  intCompare.sh
  list.bak
  testFor.sh
  whoson.sh
  • C나 Java에서 사용하는 형태

  •   for (( exp1; exp2; exp3 )); do
        command...
      done
  • exp1~3은 수식으로 각각 생략 가능

  • exp1은 제어 변수의 초기화를 위해 한 번 수행 됨

  • exp2가 참인 동안 명령과 exp3이 반복 수행 됨

  • [ec2-user@ip-AWS ~]$ cat testFor3.sh
      #! /bin/bash
      LIMIT=10
    
      for(( a=0; a<LIMIT; a++)); do
        echo "$a"
      done
      [ec2-user@ip-AWS ~]$ . testFor3.sh
      0
      1
      2
      3
      4
      5
      6
      7
      8
      9
      [ec2-user@ip-AWS ~]$

while

  • 조건이 참인 동안 명령을 반복함.
  •   while command...; do
        command
      done
  • while 다음에 나오는 명령을 실행하여 참 또는 거짓을 판단함
  • if 명령과 마찬가지로 종료 상탯값이 0이면 참으로 판단
  • 조건 비교를 위해 test expression 또는 [ expression ]을 자주 사용함.
  [ec2-user@ip-AWS ~]$ cat testWhile.sh
  #! /bin/bash
  N=1
  S=0

  while [ $N -le 10 ]; do
    echo -n "$N "
    S=$[ $S+$N ]
    N=$[ $N+1 ]
  done
  echo
  echo $S
  [ec2-user@ip-AWS ~]$ . testWhile.sh
  1 2 3 4 5 6 7 8 9 10
  55

for 와 while

  • for 명령 (2)를 다음과 같이 변환 가능
  •   (( exp1 ))
      while (( exp2 )); do
        command...
        (( exp3 ))
      done
  • (( expression ))은 수식 계산에 사용되는 복합 명령
  • let "expression"과 동일하며 test 명령 대신에 사용 가능
    • 조건 비교를 위해 test expression 또는 [ expression ]과 함께 자주 사용함.
  • while 다음의 (( expression ))에서 수식 결과가 0이 아닌 경우 종료 상탯값이 0이 되며 참으로 판단.
  [ec2-user@ip-AWS ~]$ cat testWhile2.sh
  #! /bin/bash
  LIMIT=10

  ((a=0))
  while (( a<LIMIT )); do
    echo "$a"
    (( a++ ))
  done
  [ec2-user@ip-AWS ~]$ . testWhile2.sh
  0
  1
  2
  3
  4
  5
  6
  7
  8
  9

until

  • 조건이 만족될 때까지(거짓인 동안) 명령을 반복하여 수행함
  •   until command ... ; do
        command ...
      done
  • until 다음에 나오는 명령이 참이 될 때까지 반복함
    • 거짓인 동안 반복하게 됨
  • 조건을 표시하기 위해 test expression, [ expression ], (( expression ))을 사용할 수 있음.
  [ec2-user@ip-AWS ~]$ cat testUntil.sh
  #! /bin/bash
  N=1
  S=0
  until [ $N -gt 10 ]; do
    echo -n "$N "
    let S=$S+$N
    let N=$N+1
  done
  echo
  echo $S
  [ec2-user@ip-AWS ~]$ . testUntil.sh
  1 2 3 4 5 6 7 8 9 10
  55
728x90
반응형

'OS > Linux' 카테고리의 다른 글

[Linux] 원격 관리  (0) 2020.12.13
[Linnux] 네트워크 설정 및 점검  (0) 2020.12.05
[Linux] 소프트웨어 관리  (0) 2020.11.01
[Linux] 프로세스 관리  (0) 2020.11.01
[Linux] 파일 시스템 관리  (0) 2020.10.25

+ Recent posts