【问题标题】:How to store state between two consecutive runs of a bash script如何在两次连续运行的 bash 脚本之间存储状态
【发布时间】:2021-04-26 16:39:46
【问题描述】:

我有每分钟使用cron 作业运行的 bash 脚本。我想保存脚本的状态以供下次运行时重复使用。

保存状态的最佳方法是什么(在这种情况下是一个分配了数字的变量);所以在下一次运行中,该数字可以与之前运行的值进行比较。

【问题讨论】:

  • 将状态保存到文件中,并在脚本启动时读取文件。你写/读文件有什么问题?

标签: bash persistence


【解决方案1】:

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

#!/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

【讨论】:

  • 如果有多个变量需要持久化,有什么建议如何处理?
  • @kumar 我添加了如何持久化多个变量
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2016-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多