2017-01-06 95 views
-1

如何限制shell腳本執行的次數。我試過shc,但只有時間限制而沒有使用限制。限制shell腳本執行的次數

+1

你是什麼意思?你想阻止腳本並行調用,還是希望腳本在第n次或更多時間運行時拒絕運行? – choroba

+0

是的,比如腳本已經跑了3次,第四次我希望它不運行,只是顯示一條消息,如請聯繫[email protected] –

+1

如果用戶複製腳本並運行它們呢? – choroba

回答

0

您可以使用一個文件作爲「運行計數器」並在執行過程中讀取該文件,以查看腳本以前運行過多少次。

如果您希望「numOfRuns.txt」文件在重新啓動後保留,請使用與/ tmp不同的目錄作爲根目錄。

這是一個limitedScript.sh,演示了這一點,首先沒有評論,然後用。

#!/bin/bash 

runCountFile="/tmp/numOfRuns.txt" 
maxRuns=3 

if [ -e "$runCountFile" ]; then 
    read value < "$runCountFile" 
else 
    value=0 
fi 

if ((value >= maxRuns)); then 
    echo "Script has been run too many times" 
    exit 
else 
    newValue=$((value + 1)) 
    echo $newValue > "$runCountFile" 
fi 

-

#!/bin/bash 

# limitedScript.sh: Demonstrates simple run-limiting through a file-based counter 

runCountFile="/tmp/numOfRuns.txt" # the file to store the number of times the script has run 
maxRuns=3 # maximum number of executions for this script 

if [ -e "$runCountFile" ]; then # does the run counter file exist? 
    value=`cat $runCountFile` # read the value from the file 
else 
    value=0 # the script has never run yet if the "run counter" file doesn't exist 
fi 

if ((value >= maxRuns)); then 
    echo "Script has been run too many times" 
    exit 
else 
    newValue=$((value + 1)) 
    echo $newValue > "$runCountFile" #update the "run counter" file 
fi 

OUTPUT:

[email protected]:/tmp# rm numOfRuns.txt 
[email protected]:/tmp# ./limitedScript.sh 
[email protected]:/tmp# ./limitedScript.sh 
[email protected]:/tmp# ./limitedScript.sh 
[email protected]:/tmp# ./limitedScript.sh 
Script has been run too many times 
+0

'read value <「$ runCountFile」'就足夠了,無需運行外部程序。 – chepner

+0

謝謝chepner - 更新了 – nanch

+0

有沒有辦法遠程執行此操作,因此他們無法在超過設定數量的服務器上使用腳本,或者這是不可能的 –