Created
March 22, 2016 14:13
-
-
Save caruccio/1c0f555d8ab92b5f1aee to your computer and use it in GitHub Desktop.
How to toggle a shopt flag
This file contains 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
# Lets assume you need to turn on a shopt (dotglob, for example), | |
# do some work and finally turn it back to it's original state. | |
# First we check if it's on already (shopt -q <flag>), | |
# and set a flag variable in case it was. | |
# Otherwise we turn it on and ensure the flag is clear (unset <flag>). | |
shopt -q dotglob && dotglob=1 || { shopt -s dotglob && unset dotglob; } | |
## Here we can do whatever we need to do... | |
cp -Rf /src/* /dest/dir/ | |
# Now we turn it off, but only if it was off already. | |
# If there isn't a var named (-v <flag>) we assume the shopt wasn't | |
# on when we started. | |
[ -v dotglob ] || shopt -u dotglob | |
#### | |
# You can even tur it into a pair of functions (note we use eval to set the flag) | |
shopt_on() { shopt -q $1 && eval $1=1 || { shopt -s $1 && unset $1; }; } | |
shopt_off() { [ -v $1 ] || shopt -u $1; } | |
# and use it like this | |
shopt_on dotglob | |
# do your stuff... | |
shopt_off dotglob |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment