Reputation: 13
Scenario: I have a set of .txt files inside folder and script is checking whether *.txt files exists or not
Script:
set -x
if [ -f *.txt ]
then
echo exist
else
echo not
fi
Output:
+ '[' -f 1.txt 2.txt ']'
test.sh: line 2: [: 1.txt: binary operator expected
+ echo not
not
Upvotes: 1
Views: 298
Reputation: 50750
-f
unary primary takes only one operand. You need to replace [ -f *.txt ]
with:
( set +f -- *.txt; test "$*" != '*.txt' || test -f '*.txt' )
This doesn't perform a type check on every matching file but I assume it'll suffice for your case.
+f
to set is for making sure pathname expansion is not disabled,--
is for marking the end of options,*.txt
expands to files matching *.txt
, using this with set
we're populating $*
with them,*.txt
; it will not expand to anything, it'll stay the same; with test "$*" != '*.txt'
we're checking if that's the case,*.txt
is a file named *.txt
; test -f '*.txt'
is for covering that case.As @Inian suggested, using Bash extension nullglob
we could omit the last check. Like:
( shopt -s nullglob; set +f -- *.txt; test "$*" != '' )
However, I think the most advisable approach for this task is to use find ... | read
as the condition:
find . ! -name . -prune -name '*.txt' -type f | read
Upvotes: 3