I\'m trying to write a bash function that uses nocasematch without changing the callers setting of the option. The function definition is:
is_he
You can use an associative array to remember the previous setting and then use it for reverting to the earlier setting, like this:
declare -gA _shopt_restore
shopt_set() {
local opt count
for opt; do
if ! shopt -q "$opt"; then
echo "$opt not set, setting it"
shopt -s "$opt"
_shopt_restore[$opt]=1
((count++))
else
echo "$opt set already"
fi
done
}
shopt_unset() {
local opt restore_type
for opt; do
restore_type=${_shopt_restore[$opt]}
if shopt -q "$opt"; then
echo "$opt set, unsetting it"
shopt -u "$opt"
_shopt_restore[$opt]=2
else
echo "$opt unset already"
fi
if [[ $restore_type == 1 ]]; then
unset _shopt_restore[$opt]
fi
done
}
shopt_restore() {
local opt opts restore_type
if (($# > 0)); then
opts=("$@")
else
opts=("${!_shopt_restore[@]}")
fi
for opt in "${opts[@]}"; do
restore_type=${_shopt_restore[$opt]}
case $restore_type in
1)
echo "unsetting $opt"
shopt -u "$opt"
unset _shopt_restore[$opt]
;;
2)
echo "setting $opt"
shopt -s "$opt"
unset _shopt_restore[$opt]
;;
*)
echo "$opt wasn't changed earlier"
;;
esac
done
}
Then use these functions as:
... some logic ...
shopt_set nullglob globstar # set one or more shopt options
... logic that depends on the above shopt settings
shopt_restore nullglob globstar # we are done, revert back to earlier setting
or
... some logic ...
shopt_set nullglob
... some more logic ...
shopt_set globstar
... some more logic involving shopt_set and shopt_unset ...
shopt_restore # restore everything
Complete source code here: https://github.com/codeforester/base/blob/master/lib/shopt.sh