您可以使用关联数组来记住之前的设置,然后使用它来恢复到之前的设置,如下所示:
shopt_set
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
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
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
}
然后将这些函数用作:
... 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
或者
... some logic ...
shopt_set nullglob
... some more logic ...
shopt_set globstar
... some more logic involving shopt_set and shopt_unset ...
shopt_restore # restore everything
完整的源代码在这里:https ://github.com/codeforester/base/blob/master/lib/shopt.sh