新聞中心

linux shell 腳本入門

作者: 時(shí)間:2007-04-24 來源:網(wǎng)絡(luò) 收藏

本文引用地址:http://butianyuan.cn/article/258223.htm

文件循環(huán)程序
或許您是想將所有發(fā)出的郵件保存到一個(gè)文件中的人們中的一員,但是在過了幾個(gè)月
以后,這個(gè)文件可能會變得很大以至于使對該文件的訪問速度變慢。下面的 腳本rotatefile
可以解決這個(gè)問題。這個(gè)腳本可以重命名郵件保存文件(假設(shè)為outmail)為outmail.1,
而對于outmail.1就變成了outmail.2 等等等等...
#!/bin/sh
# vim: set sw=4 ts=4 et:
ver=0.1
help()
{
cat
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
這個(gè)腳本是如何工作的呢?在檢測用戶提供了一個(gè)文件名以后,我們進(jìn)行一個(gè)9到1的循環(huán)。文件9被命名為10,文件8重命名為9等等。循環(huán)完成之后,我們將原始文件命名為文件1同時(shí)建立一個(gè)與原始文件同名的空文件。


調(diào)試 //--------------------------------------- 
//---------------------------------------


最簡單的調(diào)試命令當(dāng)然是使用echo命令。您可以使用echo在任何懷疑出錯(cuò)的地方打印任何變量值。這也是絕大多數(shù)的shell程序員要花費(fèi)80%的時(shí)間來調(diào)試程序的原因。Shell程序的好處在于不需要重新編譯,插入一個(gè)echo命令也不需要多少時(shí)間。


shell也有一個(gè)真實(shí)的調(diào)試模式。如果在腳本strangescript 中有錯(cuò)誤,您可以這樣來進(jìn)行調(diào)試:


sh -x strangescript
這將執(zhí)行該腳本并顯示所有變量的值。
shell還有一個(gè)不需要執(zhí)行腳本只是檢查語法的模式??梢赃@樣使用:
sh -n your_script
這將返回所有語法錯(cuò)誤。

更多關(guān)于Linux的技術(shù)文章,歡迎訪問 與非網(wǎng)Linux技術(shù)專區(qū)


上一頁 1 2 3 4 5 6 7 下一頁

評論


相關(guān)推薦

技術(shù)專區(qū)

關(guān)閉