[英]Increment Number (variable) in bash script
我需要在bash腳本中增加一個變量。 但是在腳本完成后,應該使用新編號導出變量,並在下次運行腳本時使用該變量。
IN MY SHELL
set x=0
SCRIPT
" If something is true.. do"
export x=$(($x+1)) //increment variable and save it for next time
if [ $x -eq 3 ];then
echo test
fi
exit
你不能在兩個進程之間將變量保存在內存中; 該值需要存儲在某處並在下次啟動時讀取。 最簡單的方法是使用文件。 (支持“通用”變量的fish
shell使用一個單獨的進程,它始終在啟動和退出時與新shell進行通信。但即使這個“master”進程也需要使用一個文件來保存它們退出時的值。 )
# Ensure that the value of x is written to the file
# no matter *how* the script exits (short of kill -9, anyway)
x_file=/some/special/file/somewhere
trap 'printf '%s\n' "$x" > "$x_file"' EXIT
x=$(cat "$x_file") # bash can read the whole file with x=$(< "$x_file")
# For a simple number, you only need to run one line
# read x < "$x_file"
x=$((x+1))
if [ "$x" -eq 3 ]; then
echo test
fi
exit
導出變量只是一種方式。 導出的變量將具有shell的所有子進程的正確值,但是當子進程退出時,父進程將丟失更改的值。 實際上,父進程只會看到變量的初始值。
這是件好事。 因為所有子進程都可能會更改導出變量的值,所以可能會為其他子進程搞亂(如果更改值是雙向的)。
你可以做兩件事之一:
source your-script.bash
或. your-script.bash
. your-script.bash
。 這樣,shell就不會創建子進程,並且變量會在同一進程中更改
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.