如何限制shell脚本的执行次数。我已经尝试了shc但是只有时间限制而不是使用限制。
答案 0 :(得分: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
输出:
root@dev:/tmp# rm numOfRuns.txt
root@dev:/tmp# ./limitedScript.sh
root@dev:/tmp# ./limitedScript.sh
root@dev:/tmp# ./limitedScript.sh
root@dev:/tmp# ./limitedScript.sh
Script has been run too many times