Linux 指令碼編寫基礎(六)

來源:互聯網
上載者:User

檔案迴圈程式

或許您是想將所有發出的郵件儲存到一個檔案中的人們中的一員,但是在過了幾個月以後,這個檔案可能會變得很大以至於使對該檔案的訪問速度變慢。下面的指令碼rotatefile可以解決這個問題。這個指令碼可以重新命名郵件儲存檔案(假設為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

這個指令碼是如何工作的呢?在檢測使用者提供了一個檔案名稱以後,我們進行一個9到1的迴圈。檔案9被命名為10,檔案8重新命名為9等等。迴圈完成之後,我們將原始檔案命名為檔案1同時建立一個與原始檔案同名的空檔案。

調試 //---------------------------------------

//---------------------------------------

最簡單的調試命令當然是使用echo命令。您可以使用echo在任何懷疑出錯的地方列印任何變數值。這也是絕大多數的shell程式員要花費80%的時間來偵錯工具的原因。Shell程式的好處在於不需要重新編譯,插入一個echo命令也不需要多少時間。

shell也有一個真實的偵錯模式。如果在指令碼"strangescript" 中有錯誤,您可以這樣來進行調試:

sh -x strangescript

這將執行該指令碼並顯示所有變數的值。

shell還有一個不需要執行指令碼只是檢查文法的模式。可以這樣使用:

sh -n your_script

這將返回所有語法錯誤。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.