bash——在运行之间存储变量的更好方法? [英] bash—Better way to store variable between runs?

查看:16
本文介绍了bash——在运行之间存储变量的更好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个 bash 脚本,我每小时使用 crontab 运行该脚本,我需要存储一个变量,以便下次运行时可以访问它.脚本每次运行时都会更改变量,因此我无法对其进行硬编码.现在我正在将其写入 txt 文件,然后再将其读回.还有比这更好的方法吗?我阅读 txt 文件的方式是我在这里找到的,我不明白,而且有点笨拙.没有内置命令吗?无论如何,这是适用的代码,其中一些变量已更改以使其更易于阅读.

I've made a bash script which I run every hour with crontab, and I need to store one variable so that I can access it the next time I run it. The script changes the variable every time it runs, so I can't hardcode it in. Right now I am writing it to a txt file and then reading it back. Is there a better way to do it than this? And the way I am reading the txt file is something I found on here, I don't understand it, and it's kinda clunky. Is there not a built in command for this? Anyway, here's the applicable code, with some of the variables changed to make it easier to read.

while read x; do
  var=$x
done < var.txt

# Do some stuff, change var to a new value

echo $var > var.txt

变量只是一个整数,所以文本文件感觉有点大材小用.

The variable is only a single integer, so the text file feels overkill.

推荐答案

没有必要使用 var;x 将在当前 shell 的范围内.或者,

There's no need to use var; x will be in scope for the current shell. Alternately,

read var < var.txt
# do stuff with var
echo $var > var.txt

<小时>

我建议使用简单的文本文件来存储变量.但是,存在自修改脚本的(非常有问题的)选项.仅供娱乐!

#!/bin/bash

read val < <( tail -n 1 "$0" )

(( val++ ))
echo "$val"

tmp=$(mktemp /tmp/XXXXXXX)
sed '$s/.*/'$val'/' "$0" > "$tmp"
mv "$tmp" "$0"

exit
0

关键是让倒数第二行是退出命令,所以它之后什么都不会执行.最后一行是你想要持久化的变量值.当脚本运行时,它从它自己的最后一行读取s.在它退出之前,它使用 sed 将自己的副本写入临时文件,并使用持久值的当前值修改最后一行.然后我们用临时文件覆盖当前脚本(假设我们有权限这样做).

The key is to have the next-to-last line be the exit command, so nothing after it will execute. The last line is the variable value you want to persist. When the script runs, it reads from its own last line. Before it exits, it uses sed to write a copy of itself toa temp file, with the last line modified with the current value of the persistent value. Then we overwrite the current script with the temp file (assuming we will have permission to do so).

但是认真的?不要这样做.

But seriously? Don't do this.

这篇关于bash——在运行之间存储变量的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆