Reputation: 1278
I want to check if there is a file matching a given pattern exists in the target directory, thus write
data_dir="/home"
sample="HT001"
r1Pattern=".R1.gz"
shopt -s nullglob
if [ -f ${data_dir}/${sample}*combined${r1Pattern} ]
then
./myscript
fi
There is NO /home/HT001_combined.R1.gz
exist. But this code kept telling me file exists. Is there anything I missed?
Thanks.
Upvotes: 1
Views: 287
Reputation: 54551
This is because of nullglob
mode. Since the file does not exist, the glob expands to nothing. And, for an empty arguement, -f
will return true if you use [
:
$ empty=
$ [ -f $empty ] && echo yes
yes
You can solve your problem by using the bash
[[
instead:
$ [[ -f $empty ]] && echo yes
[[
generally provides more predictable and friendly behavior.
EDIT:
Yeah you are right, It seems that actually the glob is not evaluated when using [[
. The way that comes to mind to do it is more like:
f=(${data_dir}/${sample}*combined${r1Pattern})
if (( ${#f[@]} == 1 )) && [[ -f ${f[0]} ]]
then
# ...
fi
This expands the glob into an array, makes sure there is exactly one result, and verifies that it is a regular file.
Upvotes: 4