Reputation: 181
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
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
Reputation: 75548
You can just use awk:
if awk 'END { exit !/pass/ }' file; then
Upvotes: 1
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