Last active
September 12, 2021 00:34
-
-
Save squito/e35ebef0b1806d9e8c34 to your computer and use it in GitHub Desktop.
working with bash variables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
my_func() {( | |
# this takes a big shortcut around doing testing & unsetting -- because this entire function | |
# is wrapped in "()", it executes in a subsell, so we can unconditionally unset, without | |
# effecting vars outside | |
unset MASTER | |
echo "do something with MASTER=${MASTER-unset}" | |
)} | |
complicated_conditional_setting_and_clearing() { | |
# leaving this here as an example of how to do testing for a variable to be cleared, with local vars, etc. | |
# as a reference, though in this particular case the trick above is simpler | |
local OLD_MASTER | |
echo "MASTER=${MASTER-unset}" | |
# see http://stackoverflow.com/questions/3601515/how-to-check-if-a-variable-is-set-in-bash/16753536#16753536 | |
if [ -n "${MASTER+x}" ]; then | |
echo "clearing MASTER" | |
OLD_MASTER=$MASTER | |
unset MASTER | |
else | |
echo "MASTER not set" | |
fi | |
echo "do something with MASTER=${MASTER-unset}" | |
if [ -n "${OLD_MASTER}" ]; then | |
echo "...now resetting ..." | |
MASTER=$OLD_MASTER | |
else | |
echo "not resetting" | |
fi | |
} | |
MASTER=foo | |
OLD_MASTER=blah | |
echo "round 1" | |
my_func | |
echo "MASTER=${MASTER-unset}" | |
echo "OLD_MASTER=${OLD_MASTER-unset}" | |
echo "" | |
MASTER="with spaces" | |
echo "round 2" | |
my_func | |
echo "MASTER=${MASTER-unset}" | |
echo "OLD_MASTER=${OLD_MASTER-unset}" | |
echo "" | |
unset MASTER | |
echo "round 3" | |
my_func | |
echo "MASTER=${MASTER-unset}" | |
echo "OLD_MASTER=${OLD_MASTER-unset}" | |
echo "" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
round 1 | |
MASTER=foo | |
clearing MASTER | |
do something with MASTER=unset | |
...now resetting ... | |
MASTER=foo | |
OLD_MASTER=blah | |
round 2 | |
MASTER=with spaces | |
clearing MASTER | |
do something with MASTER=unset | |
...now resetting ... | |
MASTER=with spaces | |
OLD_MASTER=blah | |
round 3 | |
MASTER=unset | |
MASTER not set | |
do something with MASTER=unset | |
not resetting | |
MASTER=unset | |
OLD_MASTER=blah | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment