27_Shell 언어 ― case 구문, bash 는 사용자 와 어떻게 상호작용 을 합 니까 (case, read)

케이스
앞에서 if 문 구 를 사용 하여 가 지 를 선택 하고 있 습 니 다. if 문 구 는 여러 갈래 의 조건 판단 을 완성 할 수 있 지만 코드 가 뚜렷 하지 않 고 간결 하지 않 기 때문에 본 장 은 가 지 를 선택 하 는 다른 형식 인 case 문 구 를 도입 합 니 다.이 문 구 는 if 와 큰 차이 가 없 으 며, 주요 역할 은 코드 의 논리 구 조 를 더욱 명확 하 게 하 는 것 이다.case 문장의 용법 형식 은:
 
case 변수 참조 (${}) in
value1)
문장 1
문장 2
...
;;
value2)
문장 1
문장 2
...
;;
value3)
문장 1
문장 2
...
;;
*)
문장 1
문장 2
...
;;
esac
 
다음은 예 를 들 어 케이스 의 용법 을 보 여 줍 니 다.
 
예 1: 스 크 립 트 를 작성 하면 인자 gzip, bzip 2 또는 xz 를 받 아들 일 수 있 고/etc/디 렉 터 리 압축 파일 을/backup 디 렉 터 리 에 백업 하고 매개 변수 가 지정 한 형식 으로 압축 하여 저장 할 수 있 습 니 다.파일 이름 은 스 크 립 트 실행 시간 을 포함 합 니 다.
[root@localhost tutor]# vim compress_case.sh
 
#!/bin/bash
#
 
Com=$1
 
if [ -z $Com]; then
        Com=gzip
fi
 
[ -d /backup ]|| mkdir /backup
 
case $Com in
gzip)
        tar zcf /backup/etc-`date+%F-%H-%M-%S`.tar.gz /etc/*
        RetVal=$?
        ;;
bzip2)
        tar jcf /backup/etc-`date+%F-%H-%M-%S`.tar.bz2 /etc/*
        RetVal=$?
        ;;
xz)
        tar Jcf /backup/etc-`date+%F-%H-%M-%S`.tar.xz /etc/*
        RetVal=$?
        ;;
*)
#     *        ,case         ;  case     |,    
        echo "Usage: `basename $0`{[gzip|bzip2|xz]}"
        exit 6
        ;;
esac
 
        [ $RetVal -eq 0 ] && echo"Backup etc finished.($Com)."

 
[root@localhost tutor]# ./compress_case.sh
tar: Removingleading `/' from member names
Backup etcfinished.(gzip).

[root@localhost tutor]# ls/backup
etc-2014-07-13-16-55-51.tar.gz

[root@localhost tutor]# ./compress_case.sh a
Usage:compress_case.sh {[gzip|bzip2|xz]}

[root@localhost tutor]# ./compress_case.sh xz
tar: Removingleading `/' from member names
Backup etcfinished.(xz).

[root@localhost tutor]# ls -hl/backup
total 15M
-rw-r--r--. 1root root 9.5M Jul 13 16:55 etc-2014-07-13-16-55-51.tar.gz
-rw-r--r--. 1root root 5.6M Jul 13 16:57 etc-2014-07-13-16-56-52.tar.xz

예 2. 앞에서 if 문 구 를 사용 하여 SysV 스타일 의 서비스 스 크 립 트 (26 Shell 언어 ― if 조건 판단 의 파일 테스트, 단락 조작 자) 를 쓴 적 이 있 습 니 다. 이 매개 변 수 를 받 아들 일 수 있 습 니 다. 그 사용 형식 은 다음 과 같 습 니 다.
          script.sh {start|stop|restart|status}
인자 가 start 이면 빈 파일/var/lock/subsys/script 을 만 들 고 'Starting scripts successfully.' 를 표시 합 니 다.
인자 가 stop 이면 파일/var/lock/subsys/script 을 삭제 하고 "Stop script finished."를 표시 합 니 다.
매개 변수 가 restart 이면 파일/var/lock/subsys/script 을 삭제 하고 다시 만 들 고 'Restarting scripttsuccessfully.' 를 표시 합 니 다.
인자 가 status 라면:
         /var/lock/subsys/script 파일 이 존재 하면 'script is running' 으로 표 시 됩 니 다.
          그렇지 않 으 면 'script is stopped' 로 표 시 됩 니 다.
다른 모든 인자: "script. sh {start | stop | restart | status}"를 표시 합 니 다.
이제 if 문 구 를 case 문 으로 바 꿉 니 다.
 
[root@localhost tutor]# vim service_case.sh
#!/bin/bash
#
 
SvcName=`basename$0`
LockFile=/var/lock/subsys/$SvcName
 
if [ $# -lt 1]; then
        echo "Usage: `basename $0`{start|restart|stop|status}"
        exit 5
fi
 
case $1 in
start)
        touch $LockFile
        echo "Starting $SvcNamefinished."
        ;;
stop)
        rm -f $LockFile
        echo "Stopping $SvcNamefinished."
        ;;
restart)
        rm -f $LockFile
        touch $LockFile
        echo "Restarting $SvcNamefinished."
        ;;
status)
        if [ -e $LockFile ]; then
                echo "$SvcName isrunning..."
        else
                echo "$SvcName isstoping..."
        fi
        ;;
*)
        echo "Usage: $SvcName {start|restart|stop|status}"
        exit 6
esac

 
[root@localhost tutor]# ./service_case.sh stat
Usage:service_case.sh {start|restart|stop|status}

[root@localhost tutor]# ./service_case.sh start
Startingservice_case.sh finished.

[root@localhost tutor]# ./service_case.sh restart
Restartingservice_case.sh finished.

[root@localhost tutor]# ./service_case.sh stop
Stoppingservice_case.sh finished.

[root@localhost tutor]# ./service_case.sh status
service_case.shis stoping...

 
2. bash 는 어떻게 사용자 와 상호작용 을 합 니까?
bash 언어 에 내 장 된 명령 read 가 있 습 니 다. 사용자 가 키보드 로 입력 한 내용 을 변수 에 저장 할 수 있 습 니 다.
[root@localhost tutor]# help read
read: read[-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-ttimeout] [-u fd] [name ...]
    Read a line from the standard input andsplit it into fields.
-p prompt output the string PROMPT without atrailing newline before attempting to read
\# 알림 정보 지정
-t timeout time out and return failure if acomplete line of input is not read withint TIMEOUT seconds.
\# 시간 초과 지정
 
[root@localhost tutor]# read Name
Mickey
#       Mickey     Name 

[root@localhost tutor]# echo $Name
Mickey

 
[root@localhost tutor]# read Name
Darius
#        ,         

[root@localhost tutor]# echo $Name
Darius

 
[root@localhost tutor]# read A B
13 15
# read            

 
[root@localhost tutor]# echo $A
13

[root@localhost tutor]# echo $B
15

[root@localhost tutor]# read A B
13 15 17
#              

[root@localhost tutor]# echo $A
13

[root@localhost tutor]# echo $B
15 17
#          A,        B

[root@localhost tutor]# read A B
13
#                 

[root@localhost tutor]# echo $A
13
#     A   ,  B   

 
예 1. 사용자 에 게 인 자 를 입력 하 라 고 스 크 립 트 를 작성 합 니 다.
 
[root@localhost tutor]# vim read.sh 
#!/bin/bash
 
echo -n"Please Select a Compress Method [gzip|bzip2|xz]:"
# -n       echo       
read Com
echo $Com

[root@localhost tutor]# bash read.sh
Please Selecta Compress Method [gzip|bzip2|xz]:gzip
gzip

 
상기 스 크 립 트 에서 echo 방법 을 사용 하여 사용자 에 게 파 라 메 터 를 입력 하 라 고 알려 주 었 습 니 다. 사실상 read 에 옵션 - p 를 추가 하면 사용자 에 게 알림 정 보 를 줄 수 있 기 때문에 상기 스 크 립 트 를 수정 할 수 있 습 니 다.
 
[root@localhost tutor]# vim read.sh
#!/bin/bash
 
read -p"Please Select a Compress Method [gzip|bzip2|xz]:"  Com
# -p                  
echo $Com

 
[root@localhost tutor]# bash read.sh
Please Selecta Compress Method [gzip|bzip2|xz]:bzip2
bzip2

 
- t 옵션 을 사용 하면 입력 시간 초과 도 설정 할 수 있 습 니 다.
[root@localhost tutor]# vim read.sh
#!/bin/bash
 
read -t 5 -p"Please Select a Compress Method [gzip|bzip2|xz]:"  Com
#   -t  ,       5 
echo $Com

[root@localhost tutor]# bash read.sh
PleaseSelect a Compress Method [gzip|bzip2|xz]:     
#         ,       

[root@localhost tutor]#
 
if 판단 문 구 를 사용 하여 빈 값 의 경우 기본 값 을 설정 할 수 있 습 니 다.
[root@localhost tutor]# vim read.sh
#!/bin/bash
 
read -t 5 -p"Please Select a Compress Method [gzip|bzip2|xz]:"  Com
[ -z $Com ]&& Com=gzip
#          ,      gzip
echo $Com

 
[root@localhost tutor]# bash read.sh
Please Selecta Compress Method [gzip|bzip2|xz]:gzip
#   gzip    ,  -p         

 
예 2. 스 크 립 트 를 써 서 사용자 가 입력 한 문자 가 무엇 인지 판단 합 니 다. 
 
[root@localhost tutor]# vim user_input.sh
#!/bin/bash
#
read -p"Input a Character: " Char
 
case $Char in
[0-9])
        echo "A digit."
        ;;
[[:lower:]])
        echo "A lower."
        ;;
[[:upper:]])
        echo "An upper."
        ;;
[[:punct:]])
        echo "A punction."
        ;;
*)
        echo "Special Character."
esac

 
[root@localhost tutor]# chmod +x user_input.sh
[root@localhost tutor]# ./user_input.sh
Input aCharacter: 2
A digit.

[root@localhost tutor]# ./user_input.sh
Input aCharacter: a
A lower.

[root@localhost tutor]# ./user_input.sh
Input aCharacter: A
A lower.

[root@localhost tutor]# ./user_input.sh
Input aCharacter: ,
A punction.

[root@localhost tutor]# ./user_input.sh
Input aCharacter: ^[
SpecialCharacter.

 
예 3. 사용자 가 프로 토 콜 을 받 아들 일 지 여 부 를 알려 주 는 스 크 립 트 를 작성 합 니 다.
 
[root@localhost tutor]# vim agree.sh
#!/bin/bash
#
 
read -p"Do you agree: [Yes|No]:" YesNo
 
case $YesNo in
 
y|Y|[yY][eE][sS])
        echo "Agreed, proceed...";;
n|N|[nN][oO])
        echo "Disagreed,intterupt.";;
*)
        echo "Invalid input."
esac

[root@localhost tutor]# ./agree.sh
Do you agree:[Yes|No]:yes
Agreed,proceed...

[root@localhost tutor]# ./agree.sh
Do you agree:[Yes|No]:n
Disagreed,intterupt.

[root@localhost tutor]# ./agree.sh
Do you agree:[Yes|No]:a
Invalid input.

 
예 4. 다음 메뉴 를 표시 합 니 다.
1. 다음 메뉴 를 사용자 에 게 표시 합 니 다.
m|M) showmemory usages;
d|D) showdisk usages;
q|Q) quit
2. 사용자 가 첫 번 째 항목 을 선택 하면 메모리 사용 정 보 를 표시 합 니 다.두 번 째 항목 을 선택 하면 디스크 마 운 트 및 사용 에 대한 정 보 를 표시 합 니 다.
   세 번 째 항목 이 라면 종료 하고 종료 선택 을 표시 합 니 다.다른 모든 내용 은 오류 옵션 을 설명 합 니 다.
 
[root@localhost tutor]# vim show_menu.sh
 
cat <<EOF
 
m|M showmemory usages;
d|D show diskusages;
q|Q quit
 
EOF
 
read -p"Your choice: " Choice
 
case $Choicein
m|M)
        free -m ;;
d|D)
        df -lh ;;
q|Q)
        echo "Quit..."
        exit 0 ;;
*)
        echo "Invalid input."
        exit 5
esac

 
 
[root@localhost tutor]# chmod +x show_menu.sh
[root@localhost tutor]# ./show_menu.sh 
m|M showmemory usages;
d|D show diskusages;
q|Q quit
 
Your choice: m
             total       used       free    shared    buffers     cached
Mem:           996        828        167          0        100        411
-/+ buffers/cache:        316        679
Swap:         2215          0       2215

[root@localhost tutor]# ./show_menu.sh
m|M showmemory usages;
d|D show diskusages;
q|Q quit
 
Your choice: D
Filesystem                    Size  Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root   23G 4.5G   17G  22% /
tmpfs                         499M  120K 499M   1% /dev/shm
/dev/sda1                     485M   35M 426M   8% /boot
/dev/sdb3                     9.9G   36M 9.7G   1% /mydata
/dev/sr0                      288K 288K     0 100%/media/20140715_2041

[root@localhost tutor]# ./show_menu.sh
m|M showmemory usages;
d|D show diskusages;
q|Q quit
 
Your choice: Q
Quit...

[root@localhost tutor]# ./show_menu.sh
m|M showmemory usages;
d|D show diskusages;
q|Q quit
 
Your choice: a
Invalid input.

좋은 웹페이지 즐겨찾기