Shell編程基礎(chǔ)出自Ubuntu中文本文作者:Leal 授權(quán)許可: 編輯人員:FireHare, Dbzhang800 我們可以使用任意一種文字編輯器,比如gedit、kedit、emacs、vi等來編寫shell腳本,它必須以如下行開始(必須放在文件的第一行): # !/bin/sh ...
符號#!用來告訴系統(tǒng)執(zhí)行該腳本的程序,本例使用/bin/sh。編輯結(jié)束并保存后,如果要執(zhí)行該腳本,必須先使其可執(zhí)行: chmod +x filename 此后在該腳本所在目錄下,輸入 ./filename 即可執(zhí)行該腳本。
[編輯] 變量賦值和引用Shell編程中,使用變量無需事先聲明,同時變量名的命名須遵循如下規(guī)則:
需要給變量賦值時,可以這么寫: 變量名=值 要取用一個變量的值,只需在變量名前面加一個$ ( 注意: 給變量賦值的時候,不能在"="兩邊留空格 ) #!/bin/sh # 對變量賦值: a="hello world" #等號兩邊均不能有空格存在 # 打印變量a的值: echo "A is:" $a 挑個自己喜歡的編輯器,輸入上述內(nèi)容,并保存為文件first,然后執(zhí)行 chmod +x first 使其可執(zhí)行,最后輸入 ./first 執(zhí)行該腳本。其輸出結(jié)果如下: A is: hello world 有時候變量名可能會和其它文字混淆,比如: num=2 echo "this is the $numnd" 上述腳本并不會輸出"this is the 2nd"而是"this is the ";這是由于shell會去搜索變量numnd的值,而實際上這個變量此時并沒有值。這時,我們可以用花括號來告訴shell要打印的是num變量: num=2 echo "this is the ${num}nd" 其輸出結(jié)果為:this is the 2nd
num=2 echo "this is the {$num}nd" 其輸出結(jié)果為:this is the {2}nd
var=1 var=$var+1 echo $var 打印出來的不是2而是1+1。為了達到我們想要的效果有以下幾種表達方式: let "var+=1" var=$[$var+1] var=`expr $var + 1`#注意加號兩邊的空格,否則還是按照字符串的方式賦值。 注意:前兩種方式在bash下有效,在sh下會出錯。 let表示數(shù)學(xué)運算,expr用于整數(shù)值運算,每一項用空格隔開,$[]將中括號內(nèi)的表達式作為數(shù)學(xué)運算先計算結(jié)果再輸出。 Shell腳本中有許多變量是系統(tǒng)自動設(shè)定的,我們將在用到這些變量時再作說明。除了只在腳本內(nèi)有效的普通shell變量外,還有環(huán)境變量,即那些由export關(guān)鍵字處理過的變量。本文不討論環(huán)境變量,因為它們一般只在登錄腳本中用到。 [編輯] Shell里的流程控制[編輯] if 語 句"if"表達式如果條件為真,則執(zhí)行then后的部分: if ....; then .... elif ....; then .... else .... fi 大多數(shù)情況下,可以使用測試命令來對條件進行測試,比如可以比較字符串、判斷文件是否存在及是否可讀等等……通常用" [ ] "來表示條件測試,注意這里的空格很重要,要確保方括號前后的空格。
執(zhí)行man test可以查看所有測試表達式可以比較和判斷的類型。下面是一個簡單的if語句: #!/bin/sh if [ ${SHELL} = "/bin/bash" ]; then echo "your login shell is the bash (bourne again shell)" else echo "your login shell is not bash but ${SHELL}" fi 變量$SHELL包含有登錄shell的名稱,我們拿它和/bin/bash進行比較以判斷當(dāng)前使用的shell是否為bash。 [編輯] && 和 || 操作符熟悉C語言的朋友可能會喜歡下面的表達式: [ -f "/etc/shadow" ] && echo "This computer uses shadow passwords" 這里的 && 就是一個快捷操作符,如果左邊的表達式為真則執(zhí)行右邊的語句,你也可以把它看作邏輯運算里的與操作。上述腳本表示如果/etc/shadow文件存在,則打印”This computer uses shadow passwords”。同樣shell編程中還可以用或操作(||),例如: #!/bin/sh mailfolder=/var/spool/mail/james [ -r "$mailfolder" ] || { echo "Can not read $mailfolder" ; exit 1; } echo "$mailfolder has mail from:" grep "^From " $mailfolder 該腳本首先判斷mailfolder是否可讀,如果可讀則打印該文件中的"From" 一行。如果不可讀則或操作生效,打印錯誤信息后腳本退出。需要注意的是,這里我們必須使用如下兩個命令:
我們使用花括號以匿名函數(shù)的形式將兩個命令放到一起作為一個命令使用;普通函數(shù)稍后再作說明。即使不用與和或操作符,我們也可以用if表達式完成任何事情,但是使用與或操作符會更便利很多 。 [編輯] case 語句case表達式可以用來匹配一個給定的字符串,而不是數(shù)字(可別和C語言里的switch...case混淆)。 case ... in ...) do something here esac file命令可以辨別出一個給定文件的文件類型,如:file lf.gz,其輸出結(jié)果為: lf.gz: gzip compressed data, deflated, original filename, last modified: Mon Aug 27 23:09:18 2001, os: Unix 我們利用這點寫了一個名為smartzip的腳本,該腳本可以自動解壓bzip2, gzip和zip 類型的壓縮文件: #!/bin/sh ftype=`file "$1"` # Note ' and ` is different case "$ftype" in "$1: Zip archive"*) unzip "$1" ;; "$1: gzip compressed"*) gunzip "$1" ;; "$1: bzip2 compressed"*) bunzip2 "$1" ;; *) echo "File $1 can not be uncompressed with smartzip";; esac 你可能注意到上面使用了一個特殊變量$1,該變量包含有傳遞給該腳本的第一個參數(shù)值。也就是說,當(dāng)我們運行: smartzip articles.zip $1 就是字符串 articles.zip。 [編輯] select 語句 ========================================select表達式是bash的一種擴展應(yīng)用,擅長于交互式場合。用戶可以從一組不同的值中進行選擇: select var in ... ; do break; done .... now $var can be used .... 下面是一個簡單的示例: #!/bin/sh echo "What is your favourite OS?" select var in "Linux" "Gnu Hurd" "Free BSD" "Other"; do break; done echo "You have selected $var" 如果 以上腳本運行出現(xiàn) select :NOT FOUND 將 #!/bin/sh 改為 #!/bin/bash 該腳本的運行結(jié)果如下: What is your favourite OS? 1) Linux 2) Gnu Hurd 3) Free BSD 4) Other #? 1 You have selected Linux [編輯] while/for 循環(huán)在shell中,可以使用如下循環(huán): while ...; do .... done 只要測試表達式條件為真,則while循環(huán)將一直運行。關(guān)鍵字"break"用來跳出循環(huán),而關(guān)鍵字”continue”則可以跳過一個循環(huán)的余下部分,直接跳到下一次循環(huán)中。 for循環(huán)會查看一個字符串行表(字符串用空格分隔),并將其賦給一個變量: for var in ....; do .... done 下面的示例會把A B C分別打印到屏幕上: #!/bin/sh for var in A B C ; do echo "var is $var" done 下面是一個實用的腳本showrpm,其功能是打印一些RPM包的統(tǒng)計信息: #!/bin/sh # list a content summary of a number of RPM packages # USAGE: showrpm rpmfile1 rpmfile2 ... # EXAMPLE: showrpm /cdrom/RedHat/RPMS/*.rpm for rpmpackage in $*; do if [ -r "$rpmpackage" ];then echo "=============== $rpmpackage ==============" rpm -qi -p $rpmpackage else echo "ERROR: cannot read file $rpmpackage" fi done 這里出現(xiàn)了第二個特殊變量$*,該變量包含有輸入的所有命令行參數(shù)值。如果你運行showrpm openssh.rpm w3m.rpm webgrep.rpm,那么 $* 就包含有 3 個字符串,即openssh.rpm, w3m.rpm和 webgrep.rpm。 [編輯] Shell里的一些特殊符號[編輯] 引號在向程序傳遞任何參數(shù)之前,程序會擴展通配符和變量。這里所謂的擴展是指程序會把通配符(比如*)替換成適當(dāng)?shù)奈募?,把變量替換成變量值。我們可以使用引號來防止這種擴展,先來看一個例子,假設(shè)在當(dāng)前目錄下有兩個jpg文件:mail.jpg和tux.jpg。 #!/bin/sh echo *.jpg 運行結(jié)果為: mail.jpg tux.jpg 引號(單引號和雙引號)可以防止通配符*的擴展: #!/bin/sh echo "*.jpg" echo '*.jpg' 其運行結(jié)果為: *.jpg *.jpg 其中單引號更嚴(yán)格一些,它可以防止任何變量擴展;而雙引號可以防止通配符擴展但允許變量擴展: #!/bin/sh echo $SHELL echo "$SHELL" echo '$SHELL' 運行結(jié)果為: /bin/bash /bin/bash $SHELL 此外還有一種防止這種擴展的方法,即使用轉(zhuǎn)義字符——反斜桿:\: echo \*.jpg echo \$SHELL 輸出結(jié)果為: *.jpg $SHELL [編輯] Here Document當(dāng)要將幾行文字傳遞給一個命令時,用here documents是一種不錯的方法。對每個腳本寫一段幫助性的文字是很有用的,此時如果使用here documents就不必用echo函數(shù)一行行輸出。Here document以 << 開頭,后面接上一個字符串,這個字符串還必須出現(xiàn)在here document的末尾。下面是一個例子,在該例子中,我們對多個文件進行重命名,并且使用here documents打印幫助: #!/bin/sh # we have less than 3 arguments. Print the help text: if [ $# -lt 3 ] ; then cat << HELP ren -- renames a number of files using sed regular expressions USAGE: ren 'regexp' 'replacement' files... EXAMPLE: rename all *.HTM files in *.html: ren 'HTM$' 'html' *.HTM HELP exit 0 fi OLD="$1" NEW="$2" # The shift command removes one argument from the list of # command line arguments. shift shift # $* contains now all the files: for file in $*; do if [ -f "$file" ] ; then newfile=`echo "$file" | sed "s/${OLD}/${NEW}/g"` if [ -f "$newfile" ]; then echo "ERROR: $newfile exists already" else echo "renaming $file to $newfile ..." mv "$file" "$newfile" fi fi done 這個示例有點復(fù)雜,我們需要多花點時間來說明一番。第一個if表達式判斷輸入命令行參數(shù)是否小于3個 (特殊變量$# 表示包含參數(shù)的個數(shù)) 。如果輸入?yún)?shù)小于3個,則將幫助文字傳遞給cat命令,然后由cat命令將其打印在屏幕上。打印幫助文字后程序退出。如果輸入?yún)?shù)等于或大于3個,我們就將第一個參數(shù)賦值給變量OLD,第二個參數(shù)賦值給變量NEW。下一步,我們使用shift命令將第一個和第二個參數(shù)從參數(shù)列表中刪除,這樣原來的第三個參數(shù)就成為參數(shù)列表$*的第一個參數(shù)。然后我們開始循環(huán),命令行參數(shù)列表被一個接一個地被賦值給變量$file。接著我們判斷該文件是否存在,如果存在則通過sed命令搜索和替換來產(chǎn)生新的文件名。然后將反短斜線內(nèi)命令結(jié)果賦值給newfile。這樣我們就達到了目的:得到了舊文件名和新文件名。然后使用 mv命令進行重命名 [編輯] Shell里的函數(shù)如果你寫過比較復(fù)雜的腳本,就會發(fā)現(xiàn)可能在幾個地方使用了相同的代碼,這時如果用上函數(shù),會方便很多。函數(shù)的大致樣子如下: functionname() { # inside the body $1 is the first argument given to the function # $2 the second ... body } 你需要在每個腳本的開始對函數(shù)進行聲明。 下面是一個名為xtitlebar的腳本,它可以改變終端窗口的名稱。這里使用了一個名為help的函數(shù),該函數(shù)在腳本中使用了兩次: #!/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" # 在腳本中提供幫助是一種很好的編程習(xí)慣,可以方便其他用戶(和自己)使用和理解腳本。 == 命令行參數(shù) == XXXXXXXXXXXXXXXXXXXXXXXXXX 我們已經(jīng)見過$* 和 $1, $2 ... $9 等特殊變量,這些特殊變量包含了用戶從命令行輸入的參數(shù)。迄今為止,我們僅僅了解了一些簡單的命令行語法(比如一些強制性的參數(shù)和查看幫助的-h選項)。但是在編寫更復(fù)雜的程序時,您可能會發(fā)現(xiàn)您需要更多的自定義的選項。通常的慣例是在所有可選的參數(shù)之前加一個減號,后面再加上參數(shù)值 (比如文件名)。 有好多方法可以實現(xiàn)對輸入?yún)?shù)的分析,但是下面的使用case表達式的例子無疑是一個不錯的方法。 #!/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" 你可以這樣運行該腳本: cmdparser -l hello -f -- -somefile1 somefile2 返回結(jié)果如下: opt_f is 1 opt_l is hello first arg is -somefile1 2nd arg is somefile2 這個腳本是如何工作的呢?腳本首先在所有輸入命令行參數(shù)中進行循環(huán),將輸入?yún)?shù)與case表達式進行比較,如果匹配則設(shè)置一個變量并且移除該參數(shù)。根據(jù)unix系統(tǒng)的慣例,首先輸入的應(yīng)該是包含減號的參數(shù)。 [編輯] Shell腳本示例=== 一般編程步驟=== xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 現(xiàn)在我們來討論編寫一個腳本的一般步驟。任何優(yōu)秀的腳本都應(yīng)該具有幫助和輸入?yún)?shù)。寫一個框架腳本(framework.sh),該腳本包含了大多數(shù)腳本需要的框架結(jié)構(gòu),是一個非常不錯的主意。這樣一來,當(dāng)我們開始編寫新腳本時,可以先執(zhí)行如下命令: cp framework.sh myscript 然后再插入自己的函數(shù)。 讓我們來看看如下兩個示例。 [編輯] 二進制到十進制的轉(zhuǎn)換腳本 b2d 將二進制數(shù) (比如 1101) 轉(zhuǎn)換為相應(yīng)的十進制數(shù)。這也是一個用expr命令進行數(shù)學(xué)運算的例子: #!/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" | wc -c | sed 's/ //g' ` # 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` #原來的 rval=`echo -n "$1" | cut -b 0-${numofcharminus1}`運行時出錯. #原因是cut從1開始計數(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" # 該腳本使用的算法是利用十進制和二進制數(shù)權(quán)值 (1,2,4,8,16,..),比如二進制"10"可以這樣轉(zhuǎn)換成十進制: 0 * 1 + 1 * 2 = 2 為了得到單個的二進制數(shù)我們是用了lastchar 函數(shù)。該函數(shù)使用wc –c計算字符個數(shù),然后使用cut命令取出末尾一個字符。Chop函數(shù)的功能則是移除最后一個字符。 [編輯] 文件循環(huán)拷貝你可能有這樣的需求并一直都這么做:將所有發(fā)出郵件保存到一個文件中。但是過了幾個月之后,這個文件可能會變得很大以至于該文件的訪問速度變慢;下面的腳本 rotatefile 可以解決這個問題。這個腳本可以重命名郵件保存文件(假設(shè)為outmail)為outmail.1,而原來的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 這個腳本是如何工作的呢?在檢測到用戶提供了一個文件名之后,首先進行一個9到1的循環(huán);文件名.9重命名為文件名.10,文件名.8重命名為文件名. 9……等等。循環(huán)結(jié)束之后,把原始文件命名為文件名.1,同時創(chuàng)建一個和原始文件同名的空文件(touch $filen) [編輯] 腳本調(diào)試最簡單的調(diào)試方法當(dāng)然是使用echo命令。你可以在任何懷疑出錯的地方用echo打印變量值,這也是大部分shell程序員花費80%的時間用于調(diào)試的原因。Shell腳本的好處在于無需重新編譯,而插入一個echo命令也不需要多少時間。 shell也有一個真正的調(diào)試模式,如果腳本"strangescript"出錯,可以使用如下命令進行調(diào)試: sh -x strangescript 7 上述命令會執(zhí)行該腳本,同時顯示所有變量的值。 shell還有一個不執(zhí)行腳本只檢查語法的模式,命令如下: sh -n your_script 這個命令會返回所有語法錯誤。 我們希望你現(xiàn)在已經(jīng)可以開始編寫自己的shell腳本了,盡情享受這份樂趣吧! :) |
|