from 鳥哥linux私房菜 第13章linux
shell script相似於之前的批處理文件batshell
註釋#,第一行一般是#!/bin/bash聲明這個script使用的bash的名稱vim
執行方式:./*.sh和sh *.sh是建立子進程bash,source *.sh是在父進程中直接執行sh。區別之一是*.sh中的變量是否還在父進程中。bash
命令執行控制:oop
每一個command執行完後能夠經過$?查看狀態,0表示執行成功,1表示執行失敗測試
&&: command 1 && command 2; 當command 1執行成功時才執行command 2this
||: command 1 || commnad 2; 當command 1執行失敗時才執行command 2spa
例子:command && echo "success" || echo "fail"調試
test命令測試文件的屬性:-e -f -d -r -w -x。條件判斷時用-a/-o代替&&/||code
默認變量$#, $@, $*等
接收變量$variable的兩種方式,直接執行式(在*.shh後加變量$1)和交互式(read -p "input a variable" variable)
簡單判斷符號[ ]
if then elif else fi語法
[dmtsai@study bin]$ cp ans_yn-2.sh ans_yn-3.sh [dmtsai@study bin]$ vim ans_yn-3.sh #!/bin/bash # Program: # This program shows the user's choice # History: # 2015/07/16 VBird First release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATH read -p "Please input (Y/N): " yn if [ "${yn}" == "Y" ] || [ "${yn}" == "y" ]; then echo "OK, continue" elif [ "${yn}" == "N" ] || [ "${yn}" == "n" ]; then echo "Oh, interrupt!" else echo "I don't know what your choice is" fi
case in esac語法
[dmtsai@study bin]$ vim show123.sh #!/bin/bash # Program: # This script only accepts the flowing parameter: one, two or three. # History: # 2015/07/17 VBird First release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATH echo "This program will print your selection !" # read -p "Input your choice: " choice # 暫時取消,能夠替換! # case ${choice} in # 暫時取消,能夠替換! case ${1} in # 現在使用,能夠用上面兩行替換! "one") echo "Your choice is ONE" ;; "two") echo "Your choice is TWO" ;; "three") echo "Your choice is THREE" ;; *) echo "Usage ${0} {one|two|three}" ;; esac
function語法
[dmtsai@study bin]$ vim show123-3.sh #!/bin/bash # Program: # Use function to repeat information. # History: # 2015/07/17 VBird First release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATH function printit(){ echo "Your choice is ${1}" # 這個 $1 必須要參考底下指令的下達 } echo "This program will print your selection !" case ${1} in "one") printit 1 # 請注意, printit 指令後面還有接參數! ;; "two") printit 2 ;; "three") printit 3 ;; *) echo "Usage ${0} {one|two|three}" ;; esac
循環loop
while do done與until do done
while [ "${yn}" != "yes" -a "${yn}" != "YES" ] do read -p "Please input yes/YES to stop this program: " yn done echo "OK! you input the correct answer."
until [ "${yn}" == "yes" -o "${yn}" == "YES" ] do read -p "Please input yes/YES to stop this program: " yn done echo "OK! you input the correct answer."
for do done
[dmtsai@study bin]$ vim cal_1_100-2.sh #!/bin/bash # Program: # Try do calculate 1+2+....+${your_input} # History: # 2015/07/17 VBird First release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATH read -p "Please input a number, I will count for 1+2+...+your_input: " nu s=0 for (( i=1; i<=${nu}; i=i+1 )) do s=$((${s}+${i})) done echo "The result of '1+2+3+...+${nu}' is ==> ${s}"
shell script追蹤與調試 shell -nvx *.sh