Home > database >  Why am i getting the binary operator expected error
Why am i getting the binary operator expected error

Time:04-23

I'm trying to write a shell script to check if there's a file existing that ends with .txt using an if statement. So I've tried to say if [ -f *.txt ] but it keeps giving me the same error. But when i used the same type of format for a script to tell if there's a file existing that ends with .cpp i just used the same format of if [ -f *.cpp ] and it works. I've tried using quotation marks as well like for the part where i checked if there's a file existing that ends with .jpg and i used if [ -e *."jpg" ] to get that to work and I tried it for the txt but still doesn't work.

if [ -f *.txt ]
                   then
                            for file in *.txt
                            do
                                    echo moving $file ...
                                    mv $file text
                                    filesMoved=$((filesMoved 1))
                            done
                    fi

CodePudding user response:

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
  • Related