I’m writing a very simple shell scripts that would looked at the log of all failed tests, and print out all the name of all files in the current directory that are in the log
1 #! /bin/sh
2 for file in *
3 do
4 echo "checking: $file"
5 if [$(grep $file failed.txt -c) -ne 0]
6 then
7 echo "$file FAILED"
8 fi
9 done
When I execute it, I get this error:
line 6: [0: command not found
Does anyone have any idea why?
Thanks!!
[is actually a command in linux (like bash or cat or grep).$(grep $file failed.txt -c)is a command substitution which in your case evaluated to 0. Thus the line now reads[0 -ne 0], which is interpreted as run a program called[0with arguments-ne 0].What you should write instead is
[ $(grep $file failed.txt -c) -ne 0 ]. Shell scripts require that there be spaces between the opening and closing square braces. Otherwise you change the command that is executed (the closing]indicates that there are no more arguments to be read.So now the command evaluates to
[ 0 -ne 0 ]. You can try executing this in your shell to see what happens.[exits with a value of0if the expression is true and1if it is false. You can see the exit value by echoing$?(the exit value of the last command to be run).