-1

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?

1
  • If you use quotes, the literal "file*" is tested and returns false. If unquoted, the file* could expand to more than one arguments, which is not allowed for the -f operator.
    – thanasisp
    May 26, 2022 at 11:14

1 Answer 1

0

I would use either find or a for loop to identify this situation.

Example #1 with find (using GNU extensions to limit the search space):

# First try with no matching files
[ -n "$(find /tmp/file* -maxdepth 1 -type f -print -quit)" ] && echo yes || echo no    # "no"

# Create some matching files and try the same command once more
touch /tmp/file.1 /tmp/file.43.434 /tmp/file-hegfegf
[ -n "$(find /tmp/file* -maxdepth 1 -type f -print -quit)" ] && echo yes || echo no    # "yes"

Example #2 with for loop

found=
for file in /tmp/file*
do
    [ -f "$file" ] && found=yes && break
done
[ yes = "$found" ] && echo yes || echo no    # No files "no", otherwise "yes"
5
  • OP didn't specify if file is a regular file, though can be assumed. May 26, 2022 at 11:24
  • @schrodigerscatcuriosity I think an example of [[ -f "/tmp/file*" ]] makes it pretty clear they're considering only files May 26, 2022 at 11:29
  • set -- /tmp/file*; [ -e "$1" ]
    – Kusalananda
    May 26, 2022 at 12:07
  • @roaima Ideed, I interpreted the question, not the example. May 26, 2022 at 15:15
  • @Kusalananda yes also. I hadn't considered that, but I do see it's one of the suggestions on the proposed duplicate (not a bad match, by the way) May 26, 2022 at 15:20

Not the answer you're looking for? Browse other questions tagged .