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.

1
  • The part after the pipe works fine on it's own so I'm thinking maybe I'm piping it wrong. Commented Jul 24, 2014 at 12:22

3 Answers 3

1

You can just use awk:

if awk 'END { exit !/pass/ }' file; then
Sign up to request clarification or add additional context in comments.

Comments

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"

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.