如何在bash脚本的两次连续运行之间存储状态 [英] How to store state between two consecutive runs of a bash script
本文介绍了如何在bash脚本的两次连续运行之间存储状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
cron
作业运行的bash脚本。我要保存脚本的状态以供下次运行时重复使用。
保存状态的最佳方式是什么(在本例中是分配了一个数字的变量);以便在下一次运行中,可以将该数字与以前运行的值进行比较。
推荐答案
保存并重新加载文件中的变量值的示例
#!/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
' "$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
' "$persistent_last_date"
printf 'Counter was: %d
' "$persistent_counter"
printf 'Array contained %d elements:
' "${#persistent_array[@]}"
printf '%s
' "${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
这篇关于如何在bash脚本的两次连续运行之间存储状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文