如何在 bash 脚本的两次连续运行之间存储状态

How to store state between two consecutive runs of a bash script

我有 bash 脚本,其中 运行 每分钟使用 cron 作业。我想保存脚本的状态以便在下一个 运行.

中重用

保存状态的最佳方式是什么(在本例中是一个分配了数字的变量);所以在接下来的 运行 中,该数字可以与之前 运行 中的值进行比较。

从文件保存和重新加载变量值的示例

#!/usr/bin/env bash

# The file holding persistent variable value
statefile='/var/statefile'

# Declare our variable as holding an integer
declare -i persistent_counter

# If the persistence file exists, read the variable value from it
if [ -f "$statefile" ]; then
  read -r persistent_counter <"$statefile"
else
  persistent_counter=0
fi

# Update counter
persistent_counter="$((persistent_counter + 1))"

# Save value to file
printf '%d\n' "$persistent_counter" >"$statefile"

另一种采购方式:

#!/usr/bin/env bash

# The file holding persistent variable value
statefile='/var/statefile'

# Source the statefile
. "$statefile" 2>/dev/null || :

# Declare our variable as holding an integer
declare -i persistent_counter

# Assign default value if unset
: ${persistent_counter:=0}

# Update counter
persistent_counter="$((persistent_counter + 1))"

# Persist variable to file
declare -p persistent_counter >"$statefile"

持久化多个变量(整数、字符串和数组):

#!/usr/bin/env bash

# The file holding persistent variable value
statefile='/tmp/statefile'

# Initialize variables even if they are later state restored
persistent_counter=0
persistent_last_date="never"
persistent_array=()

save_state () {
  typeset -p "$@" >"$statefile"
}

# Source the statefile to restore state
. "$statefile" 2>/dev/null || :

# Set save_state call on script exit to automatically persist state
trap 'save_state persistent_counter persistent_last_date persistent_array' EXIT

# Display restored variables
printf 'Last time script ran was: %s\n' "$persistent_last_date"
printf 'Counter was: %d\n' "$persistent_counter"
printf 'Array contained %d elements:\n' "${#persistent_array[@]}"
printf '%s\n' "${persistent_array[@]}"

# Update counter
persistent_counter="$((persistent_counter + 1))"

# Update Array
if ! [ "$persistent_last_date" = 'never' ]; then
  persistent_array+=("$persistent_last_date")
fi

# Update last run time
persistent_last_date="$(date -R)"

# Now that the script exit, it will automatically trap call save_state