stevo
stevo

Reputation: 181

Bash: if no match then execute command

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.

Upvotes: 0

Views: 2704

Answers (3)

chepner
chepner

Reputation: 531738

-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

Upvotes: 0

konsolebox
konsolebox

Reputation: 75548

You can just use awk:

if awk 'END { exit !/pass/ }' file; then

Upvotes: 1

fedorqui
fedorqui

Reputation: 290015

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"

Upvotes: 0

Related Questions