In bash, if you do this:
mkdir /tmp/empty array=(/tmp/empty/*)
you find that array
now has one element, "/tmp/empty/*"
, not zero as you'd like. Thankfully, this can be avoided by turning on the nullglob shell option using shopt -s nullglob
But nullglob is global, and when editing an existing shell script, may break things (e.g., did someone check the exit code of ls foo*
to check if there are files named starting with "foo"?). So, ideally, I'd like to turn it on only for a small scope—ideally, one filename expansion. You can turn it off again using shopt -u nullglob
But of course only if it was disabled before:
old_nullglob=$(shopt -p | grep 'nullglob$') shopt -s nullglob array=(/tmp/empty/*) eval "$old_nullglob" unset -v old_nullglob
makes me think there must be a better way. The obvious "put it in a subshell" doesn't work as of course the variable assignment dies with the subshell. Other than waiting for the Austin group to import ksh93 syntax, is there?
Nullglob is what you're looking for. Nullglob, quoting shopts man page, “allows filename patterns which match no files to expand to a null string, rather than themselves”.
Shopt is a built-in command in Unix-like operating systems, such as macOS and Linux distributions. The “shopt” command provides control over many settings that are used to tweak the operations in a Bash shell.
Unset it when done:
shopt -u nullglob
And properly (i.e. storing the previous state):
shopt -u | grep -q nullglob && changed=true && shopt -s nullglob ... do whatever you want ... [ $changed ] && shopt -u nullglob; unset changed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With