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
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:
#!/bin/bash
shellglob='*.sh'
scripts=($shellglob)
if [ -e "${scripts[0]}" ]
then stat "${scripts[@]}"
fi
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 without nullglob
, you'll want
if [ "${scripts[*]}" ] && [ -e "${scripts[0]}" ]
An 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.