Shell腳本編程學習入門:Shell編程基礎
#!/bin/sh ...
注意:***使用“!/bin/bash”而不是“!/bin/sh”,如果使用tc shell改為tcsh,其他類似。
符號#!用來告訴系統執行該sell腳本的程序,本例使用/bin/sh。編輯結束并保存后,如果要執行該shell腳本,必須先使其可執行:
chmod +x filename
此后在該shell腳本所在目錄下,輸入 ./filename 即可執行該shell腳本。
Shell里的一些特殊符號
a []
shell離得函數
如果你寫過比較復雜的shell腳本,就會發現可能在幾個地方使用了相同的代碼,這時如果用上函數,會方便很多。函數的大致樣子如下:
functionname()
{
# inside the body $1 is the first argument given to the function
# $2 the second ...
body
}
你需要在每個腳本的開始對函數進行聲明。
下面是一個名為xtitlebar的shell腳本,它可以改變終端窗口的名稱。這里使用了一個名為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"
#
在shell腳本中提供幫助是一種很好的編程習慣,可以方便其他用戶(和自己)使用和理解腳本。
命令行參數
我們已經見過$* 和 $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
這個shell腳本是如何工作的呢?腳本首先在所有輸入命令行參數中進行循環,將輸入參數與case表達式進行比較,如果匹配則設置一個變量并且移除該參數。根據unix系統的慣例,首先輸入的應該是包含減號的參數。
shell腳本示例
一般編程步驟
現在我們來討論編寫一個腳本的一般步驟。任何優秀的腳本都應該具有幫助和輸入參數。寫一個框架腳本(framework.sh),該shell腳本包含了大多數腳本需要的框架結構,是一個非常不錯的主意。這樣一來,當我們開始編寫新腳本時,可以先執行如下命令:
cp framework.sh myscript
然后再插入自己的函數。
讓我們來看看如下兩個示例。
#p#
二進制到十進制的轉換
腳本 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" | 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`
#原來的 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"
#
該shell腳本使用的算法是利用十進制和二進制數權值 (1,2,4,8,16,..),比如二進制"10"可以這樣轉換成十進制:
0 * 1 + 1 * 2 = 2
為了得到單個的二進制數我們是用了lastchar 函數。該函數使用wc –c計算字符個數,然后使用cut命令取出末尾一個字符。Chop函數的功能則是移除***一個字符。
#p#
文件循環轉載
你可能有這樣的需求并一直都這么做:將所有發出郵件保存到一個文件中。但是過了幾個月之后,這個文件可能會變得很大以至于該文件的訪問速度變慢;下面的shell腳本 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
這個shell腳本是如何工作的呢?在檢測到用戶提供了一個文件名之后,首先進行一個9到1的循環;文件名.9重命名為文件名.10,文件名.8重命名為文件名. 9……等等。循環結束之后,把原始文件命名為文件名.1,同時創建一個和原始文件同名的空文件(touch $filen)
腳本調試
最簡單的調試方法當然是使用echo命令。你可以在任何懷疑出錯的地方用echo打印變量值,這也是大部分shell程序員花費80%的時間用于調試的原因。Shell腳本的好處在于無需重新編譯,而插入一個echo命令也不需要多少時間。
shell也有一個真正的調試模式,如果腳本"strangescript"出錯,可以使用如下命令進行調試:
sh -x strangescript
7 上述命令會執行該腳本,同時顯示所有變量的值。
shell腳本中還有一個不執行腳本只檢查語法的模式,命令如下:
sh -n your_script
這個命令會返回所有語法錯誤。
我們希望你現在已經可以開始編寫自己的shell腳本了,盡情享受這份樂趣吧!
【編輯推薦】




















