Expert guidance for implementing and using the handle_state.sh Bash library to persist initialization state to cleanup functions, centered on the -S state-variable pattern and current hs_persist_state_as_code / hs_read_persisted_state / hs_destroy_state API. Triggers on requests like "pass information", "write initialization function" or "write cleanup function" while developing a library or code module.
Use docs/libraries/handle_state.rst as the canonical local reference for the
current API, warnings, and limitations.
config/handle_state.sh once in the main script or library entrypoint.hs_persist_state_as_code "$@" -- <local1> <local2> ....handle_state are only required to support -S.hs_read_persisted_state "$@" -- <local1> <local2> ....hs_destroy_state "$@" -- <local1> <local2> ... during cleanup.source "$(dirname "$0")/config/handle_state.sh"
init_function() {
local temp_file="/tmp/resource"
local resource_id="abc123"
hs_persist_state_as_code "$@" -- temp_file resource_id
}
cleanup_function() {
local temp_file resource_id
hs_read_persisted_state "$@" -- temp_file resource_id
rm -f "$temp_file"
echo "Cleaned $resource_id"
hs_destroy_state "$@" -- temp_file resource_id
}
local state=""
init_function -S state
cleanup_function -S state
init_function -S state
-S directly instead of hiding it."$@" to hs_persist_state_as_code,
hs_read_persisted_state, and hs_destroy_state.-- before the list of local variable names.-- is the effective separator; earlier ones may belong to the
library's own API.-- before the local names.hs_read_persisted_state "$@" -- var1 var2.eval of the raw state object in new library code.hs_read_persisted_state can emit a locally generated probe snippet when no
explicit variable list is provided, but this is best reserved for simple
cases.-- with no following variable names suppresses probe-snippet
output. This is useful when the list is generated by an expansion that can
result in zero variables, and we want the function to stay silent on stdout.-q is
supplied..github/skills/handle-state/references/templates.md.hs_read_persisted_state.The following behaviors are tracked in GitHub; avoid them or apply workarounds.
.github/skills/handle-state/references/templates.md for examples.hs_persist_state_as_code and hs_read_persisted_state still rely on
eval internally; treat state objects as trusted input only.eval "$state" in new library code.