Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to set nullglob for one glob

Tags:

bash

glob

shopt

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?

like image 766
derobert Avatar asked Feb 03 '12 09:02

derobert


People also ask

What does nullglob do?

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”.

What is Shopt?

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.


1 Answers

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 
like image 132
estani Avatar answered Oct 13 '22 11:10

estani