shell programming 經驗總結
1. 腳本的分行
經過試驗,可以將多行的shell腳本寫成一行,一次執行多個命令之間用";"分隔,控制結構可以參考man bash,這樣就可以用system函數來執行一個長腳本了。
如果將一行的腳本寫成多行(通常的做法,可讀性較好),原來控制結構的";"可以用換行符代替,原來的";"可保留可不保留。但";;"不可用一個換行符加一個";"代替.
下面是2個例子,檢查某進程是否在運行:
例1:
#!/bin/sh
#filename: sysmon.sh
#usage" sysmon.sh appname1 appname2 ...
for app in "$@" ;
do
if [ `ps -ef | grep "${app}" | grep -v "grep" | grep -v "sysmon.sh" |wc -l` == 0 ];
then
echo "/"${app}/" not running";
else
echo "/"${app}/" running";
fi
done
#-------------------------------------
#上面的代碼中各行末尾的";"可以去掉
例2:(不需要wc)
#!/bin/sh
#filename: sysmon3.sh
#usage: sysmon3.sh appname1 appname2 ...
for app in "$@";
do
if ps -ef | grep "${app}" | grep -v "grep" | grep -v "sysmon3.sh" ; then
echo "/"${app}/" running";
else
echo "/"${app}/" not running";
fi
done
#---------------------------------------
2. && 和 ";" 的區別:
";"只是分隔符, 在";'前後的命令之間沒有關聯, "&&" 和 "||"的前後命令之間有關聯, 下面是man bash裏面的描述:
Lists
A list is a sequence of one or more pipelines separated by one of the
operators ;, &, &&, or ||, and optionally terminated by one of ;, &, or
<newline>.
Of these list operators, && and || have equal precedence, followed by ;
and &, which have equal precedence.
A sequence of one or more newlines may appear in a list instead of a
semicolon to delimit commands.
If a command is terminated by the control operator &, the shell exe-
cutes the command in the background in a subshell. The shell does not
wait for the command to finish, and the return status is 0. Commands
separated by a ; are executed sequentially; the shell waits for each
command to terminate in turn. The return status is the exit status of
the last command executed.
The control operators && and || denote AND lists and OR lists, respec-
tively. An AND list has the form
command1 && command2
command2 is executed if, and only if, command1 returns an exit status
of zero.
An OR list has the form
command1 || command2
command2 is executed if and only if command1 returns a non-zero exit
status. The return status of AND and OR lists is the exit status of
the last command executed in the list.
3. while 循環
while list do list done
當list爲True時,該圈會不停地執行。
例一 : 無限迴圈寫法
#!/bin/sh
while : ; do
echo "do something forever here"
sleep 5
done
例二 : 強迫把pppd殺掉。
#!/bin/sh
while [ -f /var/run/ppp0.pid ] ; do
killall pppd
done
--------------------------------------------------------------------------------
until list do list done
當list爲False(non-zero)時,該圈會不停地執行。
例一 : 等待pppd上線。
#!/bin/sh
until [ -f /var/run/ppp0.pid ] ; do
sleep 1
done
(http://www.fanqiang.com)