Asked  7 Months ago    Answers:  5   Viewed   44 times

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



Bash specific solution:

compgen -G "<glob-pattern>"

Escape the pattern or it'll get pre-expanded into matches.

Exit status is:

  • 1 for no-match,
  • 0 for 'one or more matches'

stdout is a list of files matching the glob.
I think this is the best option in terms of conciseness and minimizing potential side effects.


if compgen -G "/tmp/someFiles*" > /dev/null; then
    echo "Some files exist."
Tuesday, June 1, 2021
answered 7 Months ago

As of PHP 5.3.2 there is the option to use the stream_resolve_include_path() function whose purpose is to

Resolve [a] filename against the include path according to the same rules as fopen()/include() does.

If the file exists on one of the include paths, then that path (including the file name) will be returned. Otherwise (i.e. the file was not on any of the include paths) it will return FALSE.

Relating this to your needs, your autoloader might look something like:

function my_autoloader($classname) {
    $found = stream_resolve_include_path($classname . '.specialversion.php');
    if ($found !== FALSE) {
        include $found;
Wednesday, March 31, 2021
answered 9 Months ago

No need to loop:

(hash.keys & keys).any? # => true


.keys returns all keys in a hash as an array. & intersects two arrays, returning any objects that exists in both arrays. Finally, .any? checks if the array intersect has any values.

Wednesday, July 28, 2021
answered 5 Months ago

It's better to use an array to hold the filenames. A string variable will not handle filenames which contain spaces.

Also, you don't need to use the basename command. Instead use bash's built-in string manipulation.

Try this:

files=( /very/long/path/to/various/files/*.file )
for file in "${files[@]}"
  echo "$filenameWithoutExtension"
Friday, August 13, 2021
answered 4 Months ago
shopt -s extglob
rm -- !(Folder-???)
Thursday, November 4, 2021
David LeBauer
answered 1 Month ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :