If I want to check for the existence of a single file, I can test for it using test -e filename
or [ -e filename ]
.
Supposing I have a glob and I want to know whether any files exist whose names match the glob. The glob can match 0 files (in which case I need to do nothing), or it can match 1 or more files (in which case I need to do something). How can I test whether a glob has any matches? (I don't care how many matches there are, and it would be best if I could do this with one if
statement and no loops (simply because I find that most readable).
(test -e glob*
fails if the glob matches more than one file.)
In Bash, you can glob to an array; if the glob didn't match, your array will contain a single entry that doesn't correspond to an existing file:
Note: if you have
nullglob
set,scripts
will be an empty array, and you should test with[ "${scripts[*]}" ]
or with[ "${#scripts[*]}" != 0 ]
instead. If you're writing a library that must work with or withoutnullglob
, you'll wantAn advantage of this approach is that you then have the list of files you want to work with, rather than having to repeat the glob operation.
I did not see this answer, so I thought I'd put it out there:
To simplify The MYYN's answer somewhat, based on his idea:
[
ls glob* 2>/dev/null | head -n 1
] && echo truetest -e has the unfortunate caveat that it considers broken symbolic links to not exist. So you may want to check for those, too.