简体   繁体   English

bash脚本中的增量编号(变量)

[英]Increment Number (variable) in bash script

I need to increment a number inside a varaible in a bash script. 我需要在bash脚本中增加一个变量。 But after the script is done, the variable should be exported with the new number and available next time the script is running. 但是在脚本完成后,应该使用新编号导出变量,并在下次运行脚本时使用该变量。

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

You cannot persist a variable in memory between two processes; 你不能在两个进程之间将变量保存在内存中; the value needs to be stored somewhere and read on the next startup. 该值需要存储在某处并在下次启动时读取。 The simplest way to do this is with a file. 最简单的方法是使用文件。 (The fish shell, which supports "universal" variables, uses a separate process that always runs to communicate with new shells as they start and exit. But even this "master" process needs to use a file to save the values when it exits.) (支持“通用”变量的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

Exporting a variable is one way only. 导出变量只是一种方式。 The exported variable will have the correct value for all child processes of your shell, but when the child exits, the changed value is lost for the parent process. 导出的变量将具有shell的所有子进程的正确值,但是当子进程退出时,父进程将丢失更改的值。 Actually, the parent process will only see the initial value of the variable. 实际上,父进程只会看到变量的初始值。

Which is a good thing. 这是件好事。 Because all child processes can potentially change the value of an exported variable, potentially messing things up for the other child processes (if changing the value would be bi-directional). 因为所有子进程都可能会更改导出变量的值,所以可能会为其他子进程搞乱(如果更改值是双向的)。

You could do one of two things: 你可以做两件事之一:

  • Have the script save the value to a file before exiting, and reading it from the file when starting 让脚本在退出之前将值保存到文件中,并在启动时从文件中读取它
  • Use source your-script.bash or . your-script.bash 使用source your-script.bash. your-script.bash . your-script.bash . . your-script.bash This way, your shell will not create a child process, and the variable gets changed in same process 这样,shell就不会创建子进程,并且变量会在同一进程中更改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM