可以使用trap
在強力呼籲sed
對終止或退出更新文件中的索引。例如:
#!/bin/bash
declare -i current_idx=0
trap 'sed -i "s/^declare[ ]-i[ ]current_idx[=].*$/declare -i \
current_idx=$(((current_idx+1) % 4))/" $(readlink -f "$0")' SIGTERM EXIT
case "$current_idx" in
0) printf "picked up %d entry\n" "$current_idx";;
1) printf "picked up %d entry\n" "$current_idx";;
2) printf "picked up %d entry\n" "$current_idx";;
3) printf "picked up %d entry\n" "$current_idx";;
*) printf "error: current_idx is '%d'\n" "$current_idx";;
esac
實施例使用
這裏是稱爲11倍的腳本顯示它循環通過4個不同的條目返回到第一對第五呼叫如何。
$ (for i in {0..10}; do bash selfmod.sh; done)
picked up 0 entry
picked up 1 entry
picked up 2 entry
picked up 3 entry
picked up 0 entry
picked up 1 entry
picked up 2 entry
picked up 3 entry
picked up 0 entry
picked up 1 entry
picked up 2 entry
注:自我修改的劇本是不是好的做法。你的單獨檔案的想法更安全。但是,爲了您的目的,這將起作用。但是,我沒有表示這是多麼明智或安全。