Bash:每次运行该脚本时从脚本中增加一个变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18296321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:17:30  来源:igfitidea点击:

Bash: increment a variable from a script every time when I run that script

bashincrementauto-increment

提问by Radu R?deanu

I want that a variable from a script to be incremented every time when I run that script. Something like this:

我希望每次运行该脚本时,脚本中的变量都会增加。像这样的东西:

#!/bin/bash    
n=0   #the variable that I want to be incremented
next_n=$[$n+1]
sed -i "2s/.*/n=$next_n/" 
#!/bin/bash    
n=0;#the variable that I want to be incremented
next_n=$[$n+1]
sed -i "/#the variable that I want to be incremented$/s/=.*#/=$next_n;#/" 
(( n++ ))
echo $n
echo $n

will do the job, but is not so good if I will add other lines to the script before the line in which the variable is set and I forget to update the line sed -i "2s/.*/n=$next_n/" ${0}.

将完成这项工作,但如果我将其他行添加到设置变量的行之前的脚本中并且我忘记更新该行,则效果不佳sed -i "2s/.*/n=$next_n/" ${0}

Also I prefer to not use another file in which to keep the variable value.

我也不想使用另一个文件来保存变量值。

Some other idea?

还有什么想法?

回答by eeeyes

[[ -f saved_value ]] || echo 0 > saved_value
n=$(< saved_value)
echo $(( n + 1 )) > saved_value

回答by choroba

A script is run in a subshell, which means its variables are forgotten once the script ends and are not propagated to the parent shell which called it. To run a command list in the current shell, you could either sourcethe script, or write a function. In such a script, plain

脚本在子 shell 中运行,这意味着一旦脚本结束,它的变量就会被遗忘,并且不会传播到调用它的父 shell。要在当前 shell 中运行命令列表,您可以使用source脚本或编写函数。在这样的脚本中,简单的

##代码##

would work - but only when called from the same shell. If the script should work from different shells, or even after switching the machine off and on again, saving the value in a file is the simplest and best option. It might be easier, though, to store the variable value in a different file, not the script itself:

会工作 - 但仅当从同一个 shell 调用时。如果脚本应该在不同的 shell 中工作,或者甚至在关闭和重新打开机器之后,将值保存在文件中是最简单和最好的选择。但是,将变量值存储在不同的文件中可能更容易,而不是脚本本身:

##代码##

Changing the script when it runs might have strange consequences, especially when you change the size of the script (which might happen at 9 → 10).

在脚本运行时更改脚本可能会产生奇怪的结果,尤其是当您更改脚本的大小时(这可能发生在 9 → 10)。