diff --git a/build-sbx.sh b/build-sbx.sh index a461bec..f7e8258 100755 --- a/build-sbx.sh +++ b/build-sbx.sh @@ -15,6 +15,10 @@ set -o pipefail readonly KIT_PATH="$HOME/.sbx/kits/hypoport.ai" readonly TEMPLATE='127.0.0.1:62735/finmas.de/mux033/opencode-ops:latest' +# This is intentionally global because the EXIT cleanup function runs after +# `main` has returned and therefore cannot access `main`'s local variables. +tmp='' + require_command() { local command_name="$1" local message="$2" @@ -79,6 +83,15 @@ prompt_component() { done } +cleanup_temporary_directory() { + # EXIT traps run after `main` returns, so a variable declared local inside + # `main` is no longer available. `${tmp:-}` also keeps nounset from + # turning normal script completion into an error when no copy was made. + if [[ -n "${tmp:-}" ]]; then + rm -rf -- "$tmp" + fi +} + main() { # Check dependencies before asking questions. A missing tool should not # leave the user halfway through an interactive setup. @@ -193,7 +206,7 @@ main() { done fi - local tmp='' api_key + local api_key if [[ "$build_from_scratch" == false ]]; then # `sbx cp` needs a host-side intermediary. `mktemp` gives concurrent # runs separate directories, and the EXIT trap removes the copy even @@ -202,7 +215,7 @@ main() { printf 'Unable to create a temporary directory.\n' >&2 exit 1 } - trap 'rm -rf "${tmp:?}"' EXIT + trap cleanup_temporary_directory EXIT # Copy before creating the new sandbox so a failed creation cannot # destroy the only temporary copy of the source data.