Shell腳本編程學(xué)習(xí)入門(mén):Shell編程基礎(chǔ)
#!/bin/sh ...
注意:***使用“!/bin/bash”而不是“!/bin/sh”,如果使用tc shell改為tcsh,其他類似。
符號(hào)#!用來(lái)告訴系統(tǒng)執(zhí)行該sell腳本的程序,本例使用/bin/sh。編輯結(jié)束并保存后,如果要執(zhí)行該shell腳本,必須先使其可執(zhí)行:
chmod +x filename
此后在該shell腳本所在目錄下,輸入 ./filename 即可執(zhí)行該shell腳本。
Shell里的一些特殊符號(hào)
a []
shell離得函數(shù)
如果你寫(xiě)過(guò)比較復(fù)雜的shell腳本,就會(huì)發(fā)現(xiàn)可能在幾個(gè)地方使用了相同的代碼,這時(shí)如果用上函數(shù),會(huì)方便很多。函數(shù)的大致樣子如下:
functionname() { # inside the body $1 is the first argument given to the function # $2 the second ... body }
你需要在每個(gè)腳本的開(kāi)始對(duì)函數(shù)進(jìn)行聲明。
下面是一個(gè)名為xtitlebar的shell腳本,它可以改變終端窗口的名稱。這里使用了一個(gè)名為help的函數(shù),該函數(shù)在shell腳本中使用了兩次:
#!/bin/sh # vim: set sw=4 ts=4 et: help() { cat << HELP xtitlebar -- change the name of an xterm, gnome-terminal or kde konsole USAGE: xtitlebar [-h] "string_for_titelbar" OPTIONS: -h help text EXAMPLE: xtitlebar "cvs" HELP exit 0 } # in case of error or if -h is given we call the function help: [ -z "$1" ] && help [ "$1" = "-h" ] && help # send the escape sequence to change the xterm titelbar: echo -e "33]0;$107" #
在shell腳本中提供幫助是一種很好的編程習(xí)慣,可以方便其他用戶(和自己)使用和理解腳本。
命令行參數(shù)
我們已經(jīng)見(jiàn)過(guò)$* 和 $1, $2 ... $9 等特殊變量,這些特殊變量包含了用戶從命令行輸入的參數(shù)。迄今為止,我們僅僅了解了一些簡(jiǎn)單的命令行語(yǔ)法(比如一些強(qiáng)制性的參數(shù)和查看幫助的-h選項(xiàng))。但是在編寫(xiě)更復(fù)雜的程序時(shí),您可能會(huì)發(fā)現(xiàn)您需要更多的自定義的選項(xiàng)。通常的慣例是在所有可選的參數(shù)之前加一個(gè)減號(hào),后面再加上參數(shù)值 (比如文件名)。
有好多方法可以實(shí)現(xiàn)對(duì)輸入?yún)?shù)的分析,但是下面的使用case表達(dá)式的例子無(wú)疑是一個(gè)不錯(cuò)的方法。
#!/bin/sh help() { cat << HELP This is a generic command line parser demo. USAGE EXAMPLE: cmdparser -l hello -f -- -somefile1 somefile2 HELP exit 0 } while [ -n "$1" ]; do case $1 in -h) help;shift 1;; # function help is called -f) opt_f=1;shift 1;; # variable opt_f is set -l) opt_l=$2;shift 2;; # -l takes an argument -> shift by 2 --) shift;break;; # end of options -*) echo "error: no such option $1. -h for help";exit 1;; *) break;; esac done echo "opt_f is $opt_f" echo "opt_l is $opt_l" echo "first arg is $1" echo "2nd arg is $2"
你可以這樣運(yùn)行該腳本:
cmdparser -l hello -f -- -somefile1 somefile2
返回結(jié)果如下:
opt_f is 1 opt_l is hello first arg is -somefile1 2nd arg is somefile2
這個(gè)shell腳本是如何工作的呢?腳本首先在所有輸入命令行參數(shù)中進(jìn)行循環(huán),將輸入?yún)?shù)與case表達(dá)式進(jìn)行比較,如果匹配則設(shè)置一個(gè)變量并且移除該參數(shù)。根據(jù)unix系統(tǒng)的慣例,首先輸入的應(yīng)該是包含減號(hào)的參數(shù)。
shell腳本示例
一般編程步驟
現(xiàn)在我們來(lái)討論編寫(xiě)一個(gè)腳本的一般步驟。任何優(yōu)秀的腳本都應(yīng)該具有幫助和輸入?yún)?shù)。寫(xiě)一個(gè)框架腳本(framework.sh),該shell腳本包含了大多數(shù)腳本需要的框架結(jié)構(gòu),是一個(gè)非常不錯(cuò)的主意。這樣一來(lái),當(dāng)我們開(kāi)始編寫(xiě)新腳本時(shí),可以先執(zhí)行如下命令:
cp framework.sh myscript
然后再插入自己的函數(shù)。
讓我們來(lái)看看如下兩個(gè)示例。
#p#
二進(jìn)制到十進(jìn)制的轉(zhuǎn)換
腳本 b2d 將二進(jìn)制數(shù) (比如 1101) 轉(zhuǎn)換為相應(yīng)的十進(jìn)制數(shù)。這也是一個(gè)用expr命令進(jìn)行數(shù)學(xué)運(yùn)算的例子:
#!/bin/sh # vim: set sw=4 ts=4 et: help() { cat << HELP b2d -- convert binary to decimal USAGE: b2d [-h] binarynum OPTIONS: -h help text EXAMPLE: b2d 111010 will return 58 HELP exit 0 } error() { # print an error and exit echo "$1" exit 1 } lastchar() { # return the last character of a string in $rval if [ -z "$1" ]; then # empty string rval="" return fi # wc puts some space behind the output this is why we need sed: numofchar=`echo -n "$1" | sed 's/ //g' | wc -c ` # now cut out the last char rval=`echo -n "$1" | cut -b $numofchar` } chop() { # remove the last character in string and return it in $rval if [ -z "$1" ]; then # empty string rval="" return fi # wc puts some space behind the output this is why we need sed: numofchar=`echo -n "$1" | wc -c | sed 's/ //g' ` if [ "$numofchar" = "1" ]; then # only one char in string rval="" return fi numofcharminus1=`expr $numofchar "-" 1` # now cut all but the last char: rval=`echo -n "$1" | cut -b -$numofcharminus1` #原來(lái)的 rval=`echo -n "$1" | cut -b 0-${numofcharminus1}`運(yùn)行時(shí)出錯(cuò). #原因是cut從1開(kāi)始計(jì)數(shù),應(yīng)該是cut -b 1-${numofcharminus1} } while [ -n "$1" ]; do case $1 in -h) help;shift 1;; # function help is called --) shift;break;; # end of options -*) error "error: no such option $1. -h for help";; *) break;; esac done # The main program sum=0 weight=1 # one arg must be given: [ -z "$1" ] && help binnum="$1" binnumorig="$1" while [ -n "$binnum" ]; do lastchar "$binnum" if [ "$rval" = "1" ]; then sum=`expr "$weight" "+" "$sum"` fi # remove the last position in $binnum chop "$binnum" binnum="$rval" weight=`expr "$weight" "*" 2` done echo "binary $binnumorig is decimal $sum" #
該shell腳本使用的算法是利用十進(jìn)制和二進(jìn)制數(shù)權(quán)值 (1,2,4,8,16,..),比如二進(jìn)制"10"可以這樣轉(zhuǎn)換成十進(jìn)制:
0 * 1 + 1 * 2 = 2
為了得到單個(gè)的二進(jìn)制數(shù)我們是用了lastchar 函數(shù)。該函數(shù)使用wc –c計(jì)算字符個(gè)數(shù),然后使用cut命令取出末尾一個(gè)字符。Chop函數(shù)的功能則是移除***一個(gè)字符。
#p#
文件循環(huán)轉(zhuǎn)載
你可能有這樣的需求并一直都這么做:將所有發(fā)出郵件保存到一個(gè)文件中。但是過(guò)了幾個(gè)月之后,這個(gè)文件可能會(huì)變得很大以至于該文件的訪問(wèn)速度變慢;下面的shell腳本 rotatefile 可以解決這個(gè)問(wèn)題。這個(gè)腳本可以重命名郵件保存文件(假設(shè)為outmail)為outmail.1,而原來(lái)的outmail.1就變成了 outmail.2 等等...
#!/bin/sh # vim: set sw=4 ts=4 et: ver="0.1" help() { cat << HELP rotatefile -- rotate the file name USAGE: rotatefile [-h] filename OPTIONS: -h help text EXAMPLE: rotatefile out This will e.g rename out.2 to out.3, out.1 to out.2, out to out.1[BR] and create an empty out-file The max number is 10 version $ver HELP exit 0 } error() { echo "$1" exit 1 } while [ -n "$1" ]; do case $1 in -h) help;shift 1;; --) break;; -*) echo "error: no such option $1. -h for help";exit 1;; *) break;; esac done # input check: if [ -z "$1" ] ; then error "ERROR: you must specify a file, use -h for help" fi filen="$1" # rename any .1 , .2 etc file: for n in 9 8 7 6 5 4 3 2 1; do if [ -f "$filen.$n" ]; then p=`expr $n + 1` echo "mv $filen.$n $filen.$p" mv $filen.$n $filen.$p fi done # rename the original file: if [ -f "$filen" ]; then echo "mv $filen $filen.1" mv $filen $filen.1 fi echo touch $filen touch $filen
這個(gè)shell腳本是如何工作的呢?在檢測(cè)到用戶提供了一個(gè)文件名之后,首先進(jìn)行一個(gè)9到1的循環(huán);文件名.9重命名為文件名.10,文件名.8重命名為文件名. 9……等等。循環(huán)結(jié)束之后,把原始文件命名為文件名.1,同時(shí)創(chuàng)建一個(gè)和原始文件同名的空文件(touch $filen)
腳本調(diào)試
最簡(jiǎn)單的調(diào)試方法當(dāng)然是使用echo命令。你可以在任何懷疑出錯(cuò)的地方用echo打印變量值,這也是大部分shell程序員花費(fèi)80%的時(shí)間用于調(diào)試的原因。Shell腳本的好處在于無(wú)需重新編譯,而插入一個(gè)echo命令也不需要多少時(shí)間。
shell也有一個(gè)真正的調(diào)試模式,如果腳本"strangescript"出錯(cuò),可以使用如下命令進(jìn)行調(diào)試:
sh -x strangescript
7 上述命令會(huì)執(zhí)行該腳本,同時(shí)顯示所有變量的值。
shell腳本中還有一個(gè)不執(zhí)行腳本只檢查語(yǔ)法的模式,命令如下:
sh -n your_script
這個(gè)命令會(huì)返回所有語(yǔ)法錯(cuò)誤。
我們希望你現(xiàn)在已經(jīng)可以開(kāi)始編寫(xiě)自己的shell腳本了,盡情享受這份樂(lè)趣吧!
【編輯推薦】