Reputation: 15
I'm trying to save the current status of shopt globstar
to a variable so I can change it if needed then set it back as to not leave the user's environment altered.
I have tried storing the command output multiple ways such as var=$(command)
and var=`command`
but when I test with
echo $var
it always reads the state as "off" even though it's not.
gstar=$( shopt globstar )
echo "$gstar"
I'm hoping to use echo to test the current state against manually running shopt globstar
but they do not match.
This basic variable store is working fine with whoami
command.
Upvotes: 1
Views: 330
Reputation: 22217
To save the shopt value:
if shopt -q globstar
then
# the option is enabled
saved_globstar=-s
else
# the option is disabled
saved_globstar=-u
fi
Now you can change your globstar value. If you later want to restore it to the previous state, do a
shopt $saved_globstar globstar
Upvotes: 2
Reputation: 361635
Are you running your script directly (./script.sh
) or sourcing it (. script.sh
or source script.sh
)?
If you're running it directly it'll have its own environment and you don't have to worry about preserving the user's settings. Scripts get a copy of the user's environment and changes only affect the copy, not the original. Just set the option however you like at the top of your script.
#!/bin/bash
shopt -s globstar
foo **/bar
If it's being sourced it's a lot easier to just wrap the relevant parts of the script in a subshell so they run in an isolated environment.
(
shopt -s globstar
foo **/bar
)
baz
I suspect it's case 1 since you say it always starts out off
.
Upvotes: 4