Linux Bash 脚本中的变量,使其保持上次运行时的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9904980/
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-08-06 05:27:27  来源:igfitidea点击:

Variable in Bash Script that keeps it value from the last time running

linuxbashvariables

提问by Ferenjito

Can I create a Bash script with persistent variable-values?

我可以创建具有持久变量值的 Bash 脚本吗?

For example, I initialize a variable with 0 when the script runs for the first time (during a specific time limit), and the variable increases automatically with every time the script is running.

例如,我在脚本第一次运行时(在特定时间限制内)将变量初始化为 0,并且每次脚本运行时变量都会自动增加。

采纳答案by dldnh

you can't, but you can use a file to do it

你不能,但你可以使用一个文件来做到这一点

#!/bin/sh

# if we don't have a file, start at zero
if [ ! -f "/tmp/value.dat" ] ; then
  value=0

# otherwise read the value from the file
else
  value=`cat /tmp/value.dat`
fi

# increment the value
value=`expr ${value} + 1`

# show it to the user
echo "value: ${value}"

# and save it for next time
echo "${value}" > /tmp/value.dat

回答by Gareth Davis

I'm afraid you have to save the state in a file somewhere. The trick is to put it somewhere the user will be able to write to.

恐怕您必须将状态保存在某个文件中。诀窍是把它放在用户可以写入的地方。

yourscriptvar=0

if [ -e "$HOME/.yourscriptvar" ] ; then
    yourscriptvar=$(cat "$HOME/.yourscriptvar")
fi

# do something in your script

#save it output the file
echo $yourscriptvar > "$HOME/.yourscriptvar"

回答by Arturo Herrero

I had the same problem a few days ago and I've written my own tool to do the work because there is not other way to do something similar.

几天前我遇到了同样的问题,我编写了自己的工具来完成这项工作,因为没有其他方法可以做类似的事情。

gvaris a pure Bash key-value store where each user has a different collection of data. The records are stored in the user's home directory.

gvar是一个纯 Bash 键值存储,其中每个用户都有不同的数据集合。记录存储在用户的主目录中。

Here it is the most interesting functions from the source code:

这是源代码中最有趣的函数:

get_variable() {
  cat $FILE | grep -w  | cut -d'=' -f2
}

set_variable() {
  echo = >> $FILE
}

remove_variable() {
  sed -i.bak "/^=/d" $FILE
}