Skip to content

Instantly share code, notes, and snippets.

@slowpeek
Last active February 28, 2024 20:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slowpeek/f3e851f5c6fa6a7ba1f33d1e903bf4a9 to your computer and use it in GitHub Desktop.
Save slowpeek/f3e851f5c6fa6a7ba1f33d1e903bf4a9 to your computer and use it in GitHub Desktop.
temp.sh
# -*- mode: sh; sh-shell: bash; -*-
# shellcheck shell=bash
# MIT license (c) 2021 https://github.com/slowpeek
# Homepage: https://gist.github.com/slowpeek/f3e851f5c6fa6a7ba1f33d1e903bf4a9
# Temporarily assign a new value to a var and restore it
# later. Strings only. The code is simple on intention, use it
# correctly.
#
# temp var new_value # old=$var; var=new_value
# do_something
# temp var # var=$old; unset old
temp () {
# Flaw: it is not correct in case of declared but not set vars
# like 'declare x'. On restore such var would become set with an
# empty value.
[[ $1 == var ]] || local -n var=$1
local -n old=TE__$1
if (($# > 1)); then
! declare -p var &>/dev/null || old=${var-}
var=$2
else
if [[ -v old ]]; then
var=$old
unset -v old
else
unset -v var
fi
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment