Issue
I'm trying to write a shell script to check if there's a file existing that ends with .txt using an if statement.
Solution
Within single bracket conditionals, all of the Shell Expansions will occur, particularly in this case Filename expansion.
The condional construct acts upon the number of arguments it's given: -f
expects exactly one argument to follow it, a filename. Apparently your *.txt
pattern matches more than one file.
If your shell is bash, you can do
files=(*.txt)
if (( ${#files[@]} > 0 )); then ...
or, more portably:
count=0
for file in *.txt; do
count=1
break
done
if [ "$count" -eq 0 ]; then
echo "no *.txt files"
else
echo "at least one *.txt file"
fi
I finally get your perspective now. I've been giving you some incomplete advice. This is what you need:
for f in *.txt; do
if [ -f "$f" ]; then
do_something_with "$f"
fi
done
The reason: if there are no files matching the pattern then the shell leaves the patten as a plain string. On the first iteration of the loop, we have f="*.txt"
and mv
responds with "file not found".
I'm used to working in bash with the nullglob
option that handles this edge case.
Answered By - glenn jackman Answer Checked By - Gilberto Lyons (WPSolving Admin)