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?
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?
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"
[[ -f "/tmp/file*" ]]
makes it pretty clear they're considering only files
– Chris Davies
May 26 '22 at 11:29
could expand to more than one arguments, which is not allowed for the
-f` operator. – thanasisp May 26 '22 at 11:14