Home > Software design >  bash verify if file that ended with many combinations exists
bash verify if file that ended with many combinations exists

Time:05-26

we can have the /tmp/file.1 or /tmp/file.43.434 or /tmp/file-hegfegf , and so on

so how we can verify in bash if any /tmp/file* exists ?

we try as

[[ -f "/tmp/file*" ]] && echo "file exists" 

but above not work

how to fix it?

CodePudding user response:

for i in /tmp/file*; do
    [[ -e $i ]] && break
done

This returns 0 (success) if a matching file exists, or 1 (failure) if it doesn't, so it can be used in an if statement.

There's also the failglob and nullglob shell options, but I find the above loop to be the best. I use a similar approach to test for an empty directory (modified to check for hidden files also).

CodePudding user response:

Try

for file in /tmp/file*; do
    if [[ -f $file ]]; then
        printf "'%s' exists\\n" "$file"
        break
    fi
done
  • Related