프로그래밍/Unix

쉘 스크립트(Shell Script) 제어문 - select, continue, until 문

미냐님 2020. 5. 12. 01:05
728x90

 

until 문

  • 조건 명령이 정상 실행될 때까지 주어진 명령을 반복 실행
  • while 문과 반복 실행 조건이 반대하는 점을 제외하고는 거의 유사한 기능 제공
  • 형식
until 조건명령
do
    명령
done
  • 스크립트 예
$ cat -n test_until
1 #!/bin/bash
2 #
3 # test until loop
4 #
5
6 echo “Input name :”
7 read person
8
9 until who | grep $person # > /dev/null
10 do
11    sleep
12 done
13
14 echo “\007” # beep
$
  • 실행 결과
$ chmod +x test_until
$ ./test_until
Input name :
user2
user2 pts/3
$

 

select 문

  • 메뉴를 생성할 수 있는 루프 명령
  • list에 지정한 항목을 선택 가능한 메뉴로 만들어 화면에 출력
  • 각 항목은 순서대로 번호가 붙여짐
  • 사용자 입력을 위한 프롬프트로는 PS3 환경 변수에 저장된 문자열을 사용
  • 사용자가 입력한 값은 select와 in 사이에 지정한 변수에 저장됨
  • 형식
select 변수 in list
do
    명령
done
  • 스크립트 예
$ cat -n test_select
1 #!/bin/bash
2 #
3 # test select
4 #
5
6 PS3=“Input command(1-3) :”
7
8 select cmd in pwd date quit # pwd=1, date=2, quit=3
9 do
10    case $cmd in
11      pwd) pwd ;;
12      date) date ;;
13      quit) break ;;
14      *) echo “Invalid input, select number” ;;
15    esac
16
17    REPLY=
18 done
$
  • 실행 결과
$ chmod +x test_select
$ ./test_select
1) pwd
2) date
3) quit
Input command(1-3) :1
/home/ksshin/Unix/ch13
1) pwd
2) date
3) quit
Input command(1-3) :2
2015. 07. 15. (수) 21:54:37 (KST)
1) pwd
2) date
3) quit
Input commnad(1-3) :3
$

 

continue 문

  • continue는 루프 안에서 사용되어 이후 실행 순서를 무시하고 루프의 처음으로 돌아가는 명령
  • for, while, until, select 등 반복문을 사용해 동일한 작업을 반복하면서 조건에 따라 작업을 수행하지 않을 때 사용
  • 루트가 중첩되어 있으면 숫자를 인자로 사용해 특정 루프의 처음으로 돌아갈 수 있음
  • 스크립트 예
$ cat -n test_cont
1 #!/bin/bash
2 #
3 # test continue
4 #
5
6 for person in $(< list)
7 do
8     if [[ $person == user2 ]]
9     then
10      continue
11    fi
12
13    echo “Hello, $person ”
14 done
$
  • 실행 결과
$ chmod +x test_cont
$ ./test_cont
Hello, user3
Hello, user4
$
728x90