select
select 的語法如下,他是一個無限迴圈會一直重覆讓使用者輸入資料並執行 do done 內的 script .
select name [in list] do statements that can use $name... done
下面這個範例就是使用 select 這一無限迴圈,使用者可以選擇 1) A , 2) B , 3) C , 4) D ,並執行 do done 內的 script,需要使用 ctrl+c 來終止程式的執行.
root@ubuntu:~# vi select.sh #!/bin/bash select i in A B C D do echo your choice is ${i} done
root@ubuntu:~# ./select.sh 1) A 2) B 3) C 4) D #? 1 your choice is A #? 2 your choice is B #? 3 your choice is C #? ^C
if
可以配合 if 來使用.
if condition then statements [elif condition then statements...] [else statements] fi
修改一下程式,這樣就不需要按 ctrl+c 來終止程式的執行.選擇 5) exit 即可以離開.
root@ubuntu:~# vi select.sh #!/bin/bash select i in A B C D exit do if [ "${i}" == "exit" ]; then exit else echo your choice is ${i} fi done
root@ubuntu:~# ./select.sh 1) A 2) B 3) C 4) D 5) exit #? 1 your choice is A #? 5
case
也可以配合 case 來使用.
case expression in pattern1 ) statements ;; pattern2 ) statements ;; ... esac
修改一下程式.
#!/bin/bash select i in A B C D exit do case $i in A) echo your choice is A;; B) echo your choice is B;; C) echo your choice is C;; D) echo your choice is D;; exit) exit;; esac done
root@ubuntu:~# ./select.sh 1) A 2) B 3) C 4) D 5) exit #? 1 your choice is A #? 5
PS3
定義 PS3 ,可以讓原本 case 的輸入提示字元 #? 變成自定的輸入提示字元.
#!/bin/bash PS3="Select (1-5): " select i in A B C D exit do case $i in A) echo your choice is A;; B) echo your choice is B;; C) echo your choice is C;; D) echo your choice is D;; exit) exit;; esac done
root@ubuntu:~# ./select.sh 1) A 2) B 3) C 4) D 5) exit Select (1-5): 1 your choice is A Select (1-5): 5
沒有解決問題,試試搜尋本站其他內容