One Two Three
One Two Three

Reputation: 23547

Check the output of a command in shell script

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!!

Upvotes: 21

Views: 57257

Answers (3)

l0b0
l0b0

Reputation: 58978

Instead of testing the count, you can test the return code of grep:

if grep -q $file failed.txt &>/dev/null

Upvotes: 7

Rony
Rony

Reputation: 1734

The script can be

#!/bin/sh

for file in *; do
    echo "checking: $file"
    grep failed.txt $file && echo "$file FAILED"
done

or, as an one-liner in user shell command history:

for file in *; do { echo "checking: $file" && grep failed.txt $file && echo "$file FAILED"; done

in man grep

EXIT STATUS
The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2. (Note: POSIX error handling code should check for '2' or greater.)

Upvotes: 1

Dunes
Dunes

Reputation: 40853

[ 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 [0 with 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 of 0 if the expression is true and 1 if it is false. You can see the exit value by echoing $? (the exit value of the last command to be run).

Upvotes: 27

Related Questions