0

I want to execute a command only if a file does not contain the search. The line I'm searching is the last line of the file. Here's what I have so far:

if tail -n 1 debug.txt | [[ $( grep -q -c pass ) -eq 0 ]]; then
   echo "pass"
else
   echo "fail"
fi

This code is outputting "pass" whether the file contains that string or not.

Maybe there is a much easier way to do this too.

codeforester
  • 39,467
  • 16
  • 112
  • 140
stevo
  • 171
  • 5
  • 16
  • The part after the pipe works fine on it's own so I'm thinking maybe I'm piping it wrong. – stevo Jul 24 '14 at 12:22

3 Answers3

1

You can just use awk:

if awk 'END { exit !/pass/ }' file; then
konsolebox
  • 72,135
  • 12
  • 99
  • 105
0

You can use this one-liner:

[[ $(tail -n 1 file) == *pass* ]] && echo "pass" || echo "fail"

which is the same as:

if [[ $(tail -n 1 file) == *pass* ]]; then
    echo "pass"
else
    echo "fail"
fi

For further info: String contains in bash


If you want to check exact match, then do [ "$var" == "pass" ] comparison:

[ "$(tail -n 1 a)" == "pass" ] && echo "pass" || echo "fail"
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
0

-q prevents output to standard output; -c simply changes what grep writes to standard output, so it is still suppressed by -q. As a result, the command substitution produces an empty string in every situation, which (as an integer) is always equal to 0.

What you want is simply:

if tail -n 1 debug.txt | grep -q pass; then
   echo "pass"
else
   echo "fail"
fi
chepner
  • 497,756
  • 71
  • 530
  • 681