ubuntu shell編程基礎篇

 

1. Linux 腳本編寫基礎

1.1 語法基本介紹


1.1.1 開頭

程序必須以下面的行開始(必須方在文件的第一行):

#!/bin/sh

  符號#!用來告訴系統它後面的參數是用來執行該文件的程序。在這個例子中我們使用/bin/sh來執行程序。(可以運行echo $SHELL來看你的系統是使用那一類shell, 比如ubuntu使用的是/bin/bash,則第一行寫成#!/bin/bash)

  當編輯好腳本時,如果要執行該腳本,還必須使其可執行。 要使腳本可執行:

編譯 chmod +x filename 這樣才能用./filename 來運行


1.1.2 註釋

  在進行shell編程時,以#開頭的句子表示註釋,直到這一行的結束。我們真誠地建議您在程序中使用註釋。

如果您使用了註釋,那麼即使相當長的時間內沒有使用該腳本,您也能在很短的時間內明白該腳本的作用及工作原理。


1.1.3 變量

  在其他編程語言中您必須使用變量。在shell編程中,所有的變量都由字符串組成,並且您不需要對變量

進行聲明。要賦值給一個變量,您可以這樣寫:

#!/bin/sh

#對變量賦值(注意等號前後不能有空格,因爲加空格後a被認爲是命令名而不是一個變量):
a="hello world"

# 現在打印變量a的內容:
echo "A is:"
echo $a

有時候變量名很容易與其他文字混淆,比如:

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

賦值
let num=num+1
echo $num
打印: 3

1.1.4 環境變量

由export關鍵字處理過的變量叫做環境變量。我們不對環境變量進行討論,因爲通常情況下僅僅在登錄

腳本中使用環境變量。


1.1.5 Shell命令和流程控制

在shell腳本中可以使用三類命令:

1)Unix 命令:

  雖然在shell腳本中可以使用任意的unix命令,但是還是由一些相對更常用的命令。這些命令通常是用來進行文件和文字操作的。

常用命令語法及功能
  echo "some text": 將文字內容打印在屏幕上
  ls: 文件列表
  wc –l filewc -w filewc -c file: 計算文件行數計算文件中的單詞數計算文件中的字符數
  cp sourcefile destfile: 文件拷貝
  mv oldname newname : 重命名文件或移動文件
  rm file: 刪除文件
  grep 'pattern' file: 在文件內搜索字符串比如:grep 'searchstring' file.txt
  cut -b colnum file: 指定欲顯示的文件內容範圍,並將它們輸出到標準輸出設備比如:輸出每行第5個到第9個字符cut -b5-9 file.txt千萬不要和cat命令混淆,這是兩個完全不同的命令
  cat file.txt: 輸出文件內容到標準輸出設備(屏幕)上
  file somefile: 得到文件類型
  read var: 提示用戶輸入,並將輸入賦值給變量
  sort file.txt: 對file.txt文件中的行進行排序
  uniq: 刪除文本文件中出現的行列比如: sort file.txt | uniq
  expr: 進行數學運算Example: add 2 and 3expr 2 "+" 3
  find: 搜索文件比如:根據文件名搜索find . -name filename -print
  tee: 將數據輸出到標準輸出設備(屏幕) 和文件比如:somecommand | tee outfile
  basename file: 返回不包含路徑的文件名比如: basename /bin/tux將返回 tux
  dirname file: 返回文件所在路徑比如:dirname /bin/tux將返回 /bin
  head file: 打印文本文件開頭幾行
  tail file : 打印文本文件末尾幾行
  sed: Sed是一個基本的查找替換程序。可以從標準輸入(比如命令管道)讀入文本,並將結果輸出到標準輸出(屏幕)。該命令採用正則表達式(見參考)進行搜索。不要和shell中的通配符相混淆。比如:將linuxfocus 替換爲LinuxFocus :cat text.file | sed 's/linuxfocus/LinuxFocus/' > newtext.file。 如果要使用擴展變量則使用雙引號,比如 sed "s/number ${num}/number ${num}th/".
  awk: awk 用來從文本文件中提取字段。缺省地,字段分割符是空格,可以使用-F指定其他分割符。 cat file.txt | awk -F, '{print $1 "," $3 }'這裏我們使用,作爲字段分割符,同時打印第一個和第三個字段。如果該文件內容如下: Adam Bor, 34, IndiaKerry Miller, 22, USA 命令輸出結果爲:Adam Bor, IndiaKerry Miller, USA

2) 概念: 管道, 重定向和 backtick

  這些不是系統命令,但是他們真的很重要。

  管道 (|) 將一個命令的輸出作爲另外一個命令的輸入.

    grep "hello" file.txt | wc -l
  在file.txt中搜索包含有”hello”的行並計算其行數。在這裏grep命令的輸出作爲wc命令的輸入。當然您可以使用多個命令。

  重定向:將命令的結果輸出到文件,而不是標準輸出(屏幕)。

  > 寫入文件並覆蓋舊文件

  >> 加到文件的尾部,保留舊文件內容。

    反短斜線

  使用反短斜線( ` )可以將一個命令的輸出作爲另外一個命令的一個命令行參數。

   命令:find . -mtime -1 -type f -print
  用來查找過去24小時(-mtime –2則表示過去48小時)內修改過的文件。如果您想將所有查找到的文件打一個包,則可以使用以下腳本:

Shell代碼 
#!/bin/sh  
 
# The ticks are backticks (`) not normal quotes ('):  
tar -zcvf lastmod.tar.gz `find . -mtime -1 -type f -print` 

#!/bin/sh

# The ticks are backticks (`) not normal quotes ('):
tar -zcvf lastmod.tar.gz `find . -mtime -1 -type f -print`


3) 流程控制

1.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可以查看所有測試表達式可以比較和判斷的類型。

直接執行以下腳本:

Shell代碼 
#!/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 

#!/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進行了比較。


快捷操作符

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

[ -f "/etc/shadow" ] && echo "This computer uses shadow passwords"
這裏 && 就是一個快捷操作符,如果左邊的表達式爲真則執行右邊的語句。

您也可以認爲是邏輯運算中的與操作。上例中表示如果/etc/shadow文件存在則打印” This computer uses shadow passwords”。同樣或操作(||)在shell編程中也是可用的。這裏有個例子:

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 

#!/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表達式作任何事情,但是使用與或操作符會更便利很多。

2.case

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 類型的壓縮文件:

Shell代碼 
#!/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 

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


3. selsect

select 表達式是一種bash的擴展應用,尤其擅長於交互式使用。用戶可以從一組不同的值中進行選擇。

select var in ... ; do
 break
done
.... now $var can be used ....

下面是一個例子:

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

#!/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"
  下面是該腳本運行的結果:
What is your favourite OS?
1) Linux
2) Gnu Hurd
3) Free BSD
4) Other
#? 1
You have selected Linux


4.loop

loop表達式:
while ...; do
....
done

  while-loop 將運行直到表達式測試爲真。will run while the expression that we test for is true.關鍵字"break" 用來跳出循環。而關鍵字”continue”用來不執行餘下的部分而直接跳到下一個循環。

Shell代碼 
i=1 
while(test $i -lt 20)  
do  
     echo $i  
done 

i=1
while(test $i -lt 20)
do
     echo $i
done


    for-loop表達式查看一個字符串列表 (字符串用空格分隔) 然後將其賦給一個變量:
for var in ....; do
  ....
done

在下面的例子中,將分別打印ABC到屏幕上:

Shell代碼 
#!/bin/sh  
for var in A B C ; do  
  echo "var is $var" 
done 

#!/bin/sh
for var in A B C ; do
  echo "var is $var"
done

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

Shell代碼 
#!/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 

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

  這裏出現了第二個特殊的變量$*,該變量包含了所有輸入的命令行參數值。如果您運行showrpm openssh.rpm w3m.rpm webgrep.rpm 此時 $* 包含了 3 個字符串,即openssh.rpm, w3m.rpm and webgrep.rpm.


5. 引號

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

#!/bin/sh
echo *.jpg
這將打印出"mail.jpg tux.jpg"的結果。
引號 (單引號和雙引號) 將防止這種通配符擴展:
#!/bin/sh
echo "*.jpg"
echo '*.jpg'
這將打印"*.jpg" 兩次。單引號更嚴格一些。它可以防止任何變量擴展。雙引號可以防止通配符擴展但允許變量擴展。

#!/bin/sh
echo $SHELL
echo "$SHELL"
echo '$SHELL'

運行結果爲:
/bin/bash
/bin/bash
$SHELL

最後,還有一種防止這種擴展的方法,那就是使用轉義字符——反斜杆:
echo \*.jpg
echo \$SHELL

這將輸出:
*.jpg
$SHELL


6. Here documents

當要將幾行文字傳遞給一個命令時,here document.(譯者注:目前還沒有見到過對該詞適合的翻譯)一種不錯的方法。對每個腳本寫一段幫助性的文字是很有用的,此時如果我們四有那個here document.就不必用echo函數一行行輸出。一個 "Here document.quot; 以 << 開頭,後面接上一個字符串,這個字符串還必須出現在here document. 末尾。下面是一個例子,在該例子中,我們對多個文件進行重命名,並且使用here document.打印幫助:

Shell代碼 
#!/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 

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

functionname()
{
# inside the body $1 is the first argument given to the function
# $2 the second ...
body
}
您需要在每個程序的開始對函數進行聲明。
下面是一個叫做xtitlebar的腳本,使用這個腳本您可以改變終端窗口的名稱。這裏使用了一個叫做help的函數。正如您可以看到的那樣,這個定義的函數被使用了兩次。
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"   
#  

#!/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表達式的例子無遺是一個不錯的方法。
Shell代碼 
#!/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"  

#!/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系統的慣例,首先輸入的應該是包含減號的參數。

實例

一般編程步驟
現在我們來討論編寫一個腳本的一般步驟。任何優秀的腳本都應該具有幫助和輸入參數。並且寫一個僞腳本(framework.sh),該腳本包含了大多數腳本都需要的框架結構,是一個非常不錯的主意。這時候,在寫一個新的腳本時我們只需要執行一下copy命令:
cp framework.sh myscript
然後再插入自己的函數。
讓我們再看兩個例子:
二進制到十進制的轉換
腳本 b2d 將二進制數 (比如 1101) 轉換爲相應的十進制數。這也是一個用expr命令進行數學運算的例子:
Shell代碼 
#!/bin/sh   
# vim: set sw=4 ts=4 et:   
help()   
{   
cat <<HELP   
b2h -- convert binary to decimal   
USAGE: b2h [-h] binarynum   
OPTIONS: -h help text   
EXAMPLE: b2h 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 0-${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"   
#  

#!/bin/sh
# vim: set sw=4 ts=4 et:
help()
{
cat <<HELP
b2h -- convert binary to decimal
USAGE: b2h [-h] binarynum
OPTIONS: -h help text
EXAMPLE: b2h 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 0-${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 等等等等...
Shell代碼 
#!/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   
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  

#!/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
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同時建立一個與原始文件同名的空文件。
調試
最簡單的調試命令當然是使用echo命令。您可以使用echo在任何懷疑出錯的地方打印任何變量值。這也是絕大多數的shell程序員要花費80%的時間來調試程序的原因。Shell程序的好處在於不需要重新編譯,插入一個echo命令也不需要多少時間。
shell也有一個真實的調試模式。如果在腳本"strangescript" 中有錯誤,您可以這樣來進行調試:
sh -x strangescript
這將執行該腳本並顯示所有變量的值。
shell還有一個不需要執行腳本只是檢查語法的模式。可以這樣使用:
sh -n your_script
這將返回所有語法錯誤。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章