Shell編程基礎

本文做者:Leal

受權許可:php

編輯人員:FireHare, Dbzhang800html

咱們可使用任意一種文字編輯器,好比nedit、kedit、emacs、vi等來編寫shell腳本,它必須以以下行開始(必須放在文件的第一行): 程序員

# !/bin/sh

...

符號#!用來告訴系統執行該腳本的程序,本例使用/bin/sh。編輯結束並保存後,若是要執行該腳本,必須先使其可執行: web

chmod +x filename

此後在該腳本所在目錄下,輸入 ./filename 便可執行該腳本。 算法

 

目錄

[隱藏]

[編輯] 變量賦值和引用

Shell編程中,使用變量無需事先聲明,同時變量名的命名須遵循以下規則: shell

  1. 首個字符必須爲字母(a-z,A-Z)
  2. 中間不能有空格,可使用下劃線(_)
  3. 不能使用標點符號
  4. 不能使用bash裏的關鍵字(可用help命令查看保留關鍵字)

須要給變量賦值時,能夠這麼寫: express

變量名=值

要取用一個變量的值,只需在變量名前面加一個$ ( ATTENTION: Don't keep blank between the variable with the equal operator '=' ) 編程

#!/bin/sh
# 對變量賦值:
a="hello world"  #等號兩邊均不能有空格存在
# 打印變量a的值:
echo "A is:" $a

挑個本身喜歡的編輯器,輸入上述內容,並保存爲文件first,而後執行 chmod +x first 使其可執行,最後輸入 ./first 執行該腳本。其輸出結果以下:  ubuntu

A is: hello world

有時候變量名可能會和其它文字混淆,好比: vim

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"

其輸出結果爲:this is the 2nd

Shell腳本中有許多變量是系統自動設定的,咱們將在用到這些變量時再做說明。除了只在腳本內有效的普通shell變量外,還有環境變量,即那些由export關鍵字處理過的變量。本文不討論環境變量,由於它們通常只在登陸腳本中用到。

[編輯] Shell裏的流程控制

[編輯] if 語句

"if"表達式若是條件爲真,則執行then後的部分:

if ....; then
  ....
elif ....; then
  ....
else
  ....
fi

大多數狀況下,可使用測試命令來對條件進行測試,好比能夠比較字符串、判斷文件是否存在及是否可讀等等……一般用" [ ] "來表示條件測試,注意這裏的空格很重要,要確保方括號先後的空格。

[ -f "somefile" ] :判斷是不是一個文件
[ -x "/bin/ls" ] :判斷/bin/ls是否存在並有可執行權限
[ -n "$var" ] :判斷$var變量是否有值
[ "$a" = "$b" ] :判斷$a和$b是否相等

執行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進行比較以判斷當前使用的shell是否爲bash。

[編輯] && 和|| 操做符

熟悉C語言的朋友可能會喜歡下面的表達式:

[ -f "/etc/shadow" ] && echo "This computer uses shadow passwords"

這裏的 && 就是一個快捷操做符,若是左邊的表達式爲真則執行右邊的語句,你也能夠把它看做邏輯運算裏的與操做。上述腳本表示若是/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" 一行。若是不可讀則或操做生效,打印錯誤信息後腳本退出。須要注意的是,這裏咱們必須使用以下兩個命令:

-打印錯誤信息
-退出程序

咱們使用花括號以匿名函數的形式將兩個命令放到一塊兒做爲一個命令使用;普通函數稍後再做說明。即便不用與和或操做符,咱們也能夠用if表達式完成任何事情,可是使用與或操做符會更便利不少 。

[編輯] case 語句

case表達式能夠用來匹配一個給定的字符串,而不是數字(可別和C語言裏的switch...case混淆)。

case ... in
   ...) do something here ;;
esac

讓咱們看一個例子,file命令能夠辨別出一個給定文件的文件類型,如:file lf.gz,其輸出結果爲:

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"`
 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,該變量包含有傳遞給該腳本的第一個參數值。也就是說,當咱們運行:

smartzip articles.zip

$1 就是字符串 articles.zip。

[編輯] select 語句

select表達式是bash的一種擴展應用,擅長於交互式場合。用戶能夠從一組不一樣的值中進行選擇:

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"
  1. 若是 以上腳本運行出現 select :NOT FOUND 將 #!/bin/sh 改成 #!/bin/bash 找了半天才找到的答案

該腳本的運行結果以下:

What is your favourite OS?
1) Linux
2) Gnu Hurd
3) Free BSD
4) Other
#? 1
You have selected Linux

[編輯] while/for 循環

在shell中,可使用以下循環:

while ...; do
   ....
done

只要測試表達式條件爲真,則while循環將一直運行。關鍵字"break"用來跳出循環,而關鍵字」continue」則能夠跳過一個循環的餘下部分,直接跳到下一次循環中。

for循環會查看一個字符串行表(字符串用空格分隔),並將其賦給一個變量:

for var in ....; do
   ....
done

下面的示例會把A B C分別打印到屏幕上:

#!/bin/sh

for var in A B C ; do
   echo "var is $var"
done

下面是一個實用的腳本showrpm,其功能是打印一些RPM包的統計信息:

#!/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"dcvsdsdfasdfasdfasdfasfasf
   fi
done

這裏出現了第二個特殊變量$*,該變量包含有輸入的全部命令行參數值。若是你運行showrpm openssh.rpm w3m.rpm webgrep.rpm,那麼 $* 就包含有 3 個字符串,即openssh.rpm, w3m.rpm和 webgrep.rpm。

[編輯] Shell裏的一些特殊符號

[編輯] 引號

在向程序傳遞任何參數以前,程序會擴展通配符和變量。這裏所謂的擴展是指程序會把通配符(好比*)替換成適當的文件名,把變量替換成變量值。咱們可使用引號來防止這種擴展,先來看一個例子,假設在當前目錄下有兩個jpg文件:mail.jpg和tux.jpg。

#!/bin/sh

echo *.jpg

運行結果爲:

mail.jpg tux.jpg

引號(單引號和雙引號)能夠防止通配符*的擴展:

#!/bin/sh

echo "*.jpg"
echo '*.jpg'

其運行結果爲:

*.jpg
*.jpg

其中單引號更嚴格一些,它能夠防止任何變量擴展;而雙引號能夠防止通配符擴展但容許變量擴展:

#!/bin/sh

echo $SHELL
echo "$SHELL"
echo '$SHELL'

運行結果爲:

/bin/bash
/bin/bash
$SHELL

此外還有一種防止這種擴展的方法,即便用轉義字符——反斜杆:\:

echo \*.jpg
echo \$SHELL

輸出結果爲:

*.jpg
$SHELL

[編輯] Here documents

當要將幾行文字傳遞給一個命令時,用here documents是一種不錯的方法。對每一個腳本寫一段幫助性的文字是頗有用的,此時若是使用here documents就沒必要用echo函數一行行輸出。Here document以 << 開頭,後面接上一個字符串,這個字符串還必須出如今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

這個示例有點複雜,咱們須要多花點時間來講明一番。第一個if表達式判斷輸入命令行參數是否小於3個 (特殊變量$# 表示包含參數的個數) 。若是輸入參數小於3個,則將幫助文字傳遞給cat命令,而後由cat命令將其打印在屏幕上。打印幫助文字後程序退出。若是輸入參數等於或大於3個,咱們 就將第一個參數賦值給變量OLD,第二個參數賦值給變量NEW。下一步,咱們使用shift命令將第一個和第二個參數從參數列表中刪除,這樣原來的第三個 參數就成爲參數列表$*的第一個參數。而後咱們開始循環,命令行參數列表被一個接一個地被賦值給變量$file。接着咱們判斷該文件是否存在,若是存在則 經過sed命令搜索和替換來產生新的文件名。而後將反短斜線內命令結果賦值給newfile。這樣咱們就達到了目的:獲得了舊文件名和新文件名。而後使用 mv命令進行重命名

[編輯] Shell裏的函數

若是你寫過比較複雜的腳本,就會發現可能在幾個地方使用了相同的代碼,這時若是用上函數,會方便不少。函數的大體樣子以下:

functionname()
{
# inside the body $1 is the first argument given to the function
# $2 the second ...
body
}

你須要在每一個腳本的開始對函數進行聲明。

下面是一個名爲xtitlebar的腳本,它能夠改變終端窗口的名稱。這裏使用了一個名爲help的函數,該函數在腳本中使用了兩次:

#!/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"
#

在腳本中提供幫助是一種很好的編程習慣,能夠方便其餘用戶(和本身)使用和理解腳本。

[編輯] 命令行參數

咱們已經見過$* 和 $1, $2 ... $9 等特殊變量,這些特殊變量包含了用戶從命令行輸入的參數。迄今爲止,咱們僅僅瞭解了一些簡單的命令行語法(好比一些強制性的參數和查看幫助的-h選項)。 可是在編寫更復雜的程序時,您可能會發現您須要更多的自定義的選項。一般的慣例是在全部可選的參數以前加一個減號,後面再加上參數值 (好比文件名)。

有好多方法能夠實現對輸入參數的分析,可是下面的使用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

返回結果以下:

opt_f is 1
opt_l is hello
first arg is -somefile1
2nd arg is somefile2

這個腳本是如何工做的呢?腳本首先在全部輸入命令行參數中進行循環,將輸入參數與case表達式進行比較,若是匹配則設置一個變量而且移除該參數。根據unix系統的慣例,首先輸入的應該是包含減號的參數。

[編輯] Shell腳本示例

[編輯] 通常編程步驟

如今咱們來討論編寫一個腳本的通常步驟。任何優秀的腳本都應該具備幫助和輸入參數。寫一個框架腳本(framework.sh),該腳本包含了大多數腳本須要的框架結構,是一個很是不錯的主意。這樣一來,當咱們開始編寫新腳本時,能夠先執行以下命令:

cp framework.sh myscript

而後再插入本身的函數。

讓咱們來看看以下兩個示例。

[編輯] 二進制到十進制的轉換

腳本 b2d 將二進制數 (好比 1101) 轉換爲相應的十進制數。這也是一個用expr命令進行數學運算的例子:

#!/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開始計數,應該是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"
#

該腳本使用的算法是利用十進制和二進制數權值 (1,2,4,8,16,..),好比二進制"10"能夠這樣轉換成十進制:

0 * 1 + 1 * 2 = 2

爲了獲得單個的二進制數咱們是用了lastchar 函數。該函數使用wc –c計算字符個數,而後使用cut命令取出末尾一個字符。Chop函數的功能則是移除最後一個字符。

[編輯] 文件循環拷貝

你可能有這樣的需求並一直都這麼作:將全部發出郵件保存到一個文件中。可是過了幾個月以後,這個文件可能會變得很大以致於該文件的訪問速度變慢;下 面的腳本 rotatefile 能夠解決這個問題。這個腳本能夠重命名郵件保存文件(假設爲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的循環;文件名.9重命名爲文件名.10,文件名.8重命名爲文件 名. 9……等等。循環結束以後,把原始文件命名爲文件名.1,同時建立一個和原始文件同名的空文件(touch $filen)

[編輯] 腳本調試

最簡單的調試方法固然是使用echo命令。你能夠在任何懷疑出錯的地方用echo打印變量值,這也是大部分shell程序員花費80%的時間用於調試的緣由。Shell腳本的好處在於無需從新編譯,而插入一個echo命令也不須要多少時間。

shell也有一個真正的調試模式,若是腳本"strangescript"出錯,可使用以下命令進行調試:

sh -x strangescript

上述命令會執行該腳本,同時顯示全部變量的值。

shell還有一個不執行腳本只檢查語法的模式,命令以下:

sh -n your_script

這個命令會返回全部語法錯誤。

咱們但願你如今已經能夠開始編寫本身的shell腳本了,盡情享受這份樂趣吧! :)
相關文章
相關標籤/搜索