Search code examples
linuxbashshellcomparison

Why am I getting command not found error on numeric comparison?


I am trying to parse each line of a file and look for a particular string. The script seems to be doing its intended job, however, in parallel it tries to execute the if command on line 6:

#!/bin/bash
for line in $(cat $1)
do
echo $line | grep -e "Oct/2015"
  if($?==0); then
  echo "current line is: $line"
  fi
done

and I get the following (my script is readlines.sh)

./readlines.sh: line 6: 0==0: command not found

Solution

  • First: As Mr. Llama says, you need more spaces. Right now your script tries to look for a file named something like /usr/bin/0==0 to run. Instead:

    [ "$?" -eq 0 ] # POSIX-compliant numeric comparison
    [ "$?" = 0 ]   # POSIX-compliant string comparison
    (( $? == 0 ))  # bash-extended numeric comparison
    

    Second: Don't test $? at all in this case. In fact, you don't even have good cause to use grep; the following is both more efficient (because it uses only functionality built into bash and requires no invocation of external commands) and more readable:

    if [[ $line = *"Oct/2015"* ]]; then
      echo "Current line is: $line"
    fi
    

    If you really do need to use grep, write it like so:

    if echo "$line" | grep -q "Oct/2015"; then
      echo "Current line is: $line"
    fi
    

    That way if operates directly on the pipeline's exit status, rather than running a second command testing $? and operating on that command's exit status.