tail | grep -q always returning true - shell

When I execute this code, the loop always ends at first time (even when the last two lines of auth.log doen't contain "exit"), which means that $c always gets some string:
while true;
do
c=$(tail -2 /var/log/auth.log | grep -q "exit")
if $c ;
then
echo "true"
unset c
break
fi
done
Do you know why c=$(tail -2 /var/log/auth.log | grep -q "exit") is always getting some kind of string? I think it is becaues of tail.
I can use the -o option and then compare strings, but I prefer to use a boolean inside the if condition.

grep -q by design returns no output, it simply signals via its exit code whether a match was found.
Thus, you can simply use your pipeline directly as a condition:
while true;
do
if tail -2 /var/log/auth.log | grep -q "exit";
then
echo "true"
break
fi
done
As for what you tried:
As Benjamin W. implies in a comment on the question, executing a command expanding to the empty string is always considered a successful command.
Note: Whether the command is effectively empty because the variable in question is unset or, as in this case, was explicitly assigned a null (empty) string, doesn't matter.
Thus, given that $c is invariably empty - because grep -q by design never returns stdout output - the if condition always evaluates to true.
To be clear: $c, since it is not being used in a conditional (if $c; ... rather than if [ "$c" ]; ...), is interpreted as a command to execute rather than as a string to test for emptiness.
If the command whose output is captured in $c were to generate stdout output, you'd have to test for that with a conditional: if [ -n "$c" ]; then ... (or, more succinctly, if [ "$c" ]; then ...).

Related

What does [[ $(echo ${lines} | grep \'_SUCCESS\') ]] mean?

I came across this bash command and not able to interpret as it always print NO which is in else part.
if [[ $(echo ${lines} | grep \'_SUCCESS\') ]] ; then echo \'Y\'; else echo \'N\'; fi;
exit 0
I have _SUCCESS file ins
[[ ... ]] is a bash construct that will transform the truth value of the expression within into a exit status code 0/1. if will execute the then branch if the exit status code is 0, and the else branch otherwise.
Within [[ ... ]], you still get command substitution, so echo ${lines} | grep \'_SUCCESS\' will be executed, and its output substituted into the command. These commands will output the line inside ${lines} that contains '_SUCCESS' (with single quotes!) if such is present, or nothing.
[[ ... ]] that contains a single string evaluates as true if string is non-empty, and false if empty.
Thus, the then branch will execute if ${files} contains '_SUCCESS'. If you are always getting a 'N' as output, it follows ${files} does not contain '_SUCCESS' (even if it maybe does contain _SUCCESS). If you want to look for _SUCCESS (without quotes), then grep _SUCCESS or equivalently grep '_SUCCESS' suffices.
This is a long way around of writing what sergio says in comments: grep will not only output (or not output) the lines, it will also signal with its exit status code whether something is found or not, and can thus directly be used as the if condition, without using [[ ... ]].

How can I get the return value and matched line by grep in bash at once?

I am learning bash. I would like to get the return value and matched line by grep at once.
if cat 'file' | grep 'match_word'; then
match_by_grep="$(cat 'file' | grep 'match_word')"
read a b <<< "${match_by_grep}"
fi
In the code above, I used grep twice. I cannot think of how to do it by grep once. I am not sure match_by_grep is always empty even when there is no matched words because cat may output error message.
match_by_grep="$(cat 'file' | grep 'match_word')"
if [[ -n ${match_by_grep} ]]; then
# match_by_grep may be an error message by cat.
# So following a and b may have wrong value.
read a b <<< "${match_by_grep}"
fi
Please tell me how to do it. Thank you very much.
You can avoid the double use of grep by storing the search output in a variable and seeing if it is not empty.
Your version of the script without double grep.
#!/bin/bash
grepOutput="$(grep 'match_word' file)"
if [ ! -z "$grepOutput" ]; then
read a b <<< "${grepOutput}"
fi
An optimization over the above script ( you can remove the temporary variable too)
#!/bin/bash
grepOutput="$(grep 'match_word' file)"
[[ ! -z "$grepOutput" ]] && (read a b <<< "${grepOutput}")
Using double-grep once for checking if-condition and once to parse the search result would be something like:-
#!/bin/bash
if grep -q 'match_word' file; then
grepOutput="$(grep 'match_word' file)"
read a b <<< "${grepOutput}"
fi
When assigning a variable with a string containing a command expansion, the return code is that of the (rightmost) command being expanded.
In other words, you can just use the assignment as the condition:
if grepOutput="$(cat 'file' | grep 'match_word')"
then
echo "There was a match"
read -r a b <<< "${grepOutput}"
(etc)
else
echo "No match"
fi
Is this what you want to achieve?
grep 'match_word' file ; echo $?
$? has a return value of the command run immediately before.
If you would like to keep track of the return value, it will be also useful to have PS1 set up with $?.
Ref: Bash Prompt with Last Exit Code

Why doesn't if [ echo $foo | grep -q bar ] work?

I'm trying to read user input and compare it against a stored value as follows:
read confirm
if [ echo $confirm | grep -q y ]; then
...
fi
However, this results in a pair of errors:
[: missing `]'
grep: ]: No such file or directory
Why does this happen, and what's the appropriate alternative?
Short Answer
For your immediate use case, you simply want:
if echo "$confirm" | grep -q y; then
...or its much more efficient equivalent (if your shell is bash):
if [[ $confirm = *y* ]]; then
...or its much more efficient equivalent (for any POSIX shell):
case $confirm in *y*) echo "Put your code for the yes branch here" ;; esac
Why was the original wrong?
[ is not part of if syntax: if simply takes a (potentially compound) command as its argument before the then. [ is different name for the test command, which runs checks on its arguments; however, if what you want to test is the exit status of grep -q, then the test command doesn't need to be invoked for this purpose at all.
If you put a | inside a [ command, that makes your compound command a pipeline, and starts a new simple command. Arguments after the | are thus no longer passed to [.
With your original code:
if [ echo $confirm | grep -q y ]; then
...this was running two commands, with a pipeline between them:
[ echo $confirm # first command
grep -q y ] # second command
Since [ requires that its last argument be ], it reported that that mandatory argument was missing; and since grep treats extra arguments as filenames to read, it complained that no file named ] could be found.
Also, [ "$foo" ] checks whether the contents of foo is nonempty. Since the output of grep -q is always empty, [ "$(echo "$confirm" | grep -q y)" ], while syntactically correct, would always evaluate to false, even while exit status of grep -q changes to indicate whether a match was found. ([ "$(echo "$confirm" | grep y)" ], by contrast, is an alternative that emits a correct result - using [ ] to test whether the output from grep is or is not empty -- but is much less efficient than the best-practice approaches).
Formal if syntax
From help if:
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
The if COMMANDS list is executed. If its exit status is zero, then the
then COMMANDS list is executed. Otherwise, each elif COMMANDS list is
executed in turn, and if its exit status is zero, the corresponding
then COMMANDS list is executed and the if command completes. Otherwise,
the else COMMANDS list is executed, if present. The exit status of the
entire construct is the exit status of the last command executed, or zero
if no condition tested true.
Notably, if takes a list of COMMANDS, and no [ is included in the syntax specification.

Grep a specific string from bash script and compare

i have a large log file A.log, i want to grep ONE CERTAIN STRING from the last 10 lines and compare to a variable (FTP_SUCCESS_MSG), how can i do that?
something like:
logs='/tmp/A.log'
FTP_SUCCESS_MSG="226 Transfer complete"
if [tail -10 $logs == $FTP_SUCCESS_MSG] ;
then
echo "Success"
else
echo "Failed"
exit 1
fi
if tail -10 "$logs" | grep -Fq "$FTP_SUCCESS_MSG" ; then ...
Notice how [ is not present in the condition (and if it were, it would require non-optional spaces on both sides).
Notice also how variable interpolations are in double quotes unless you require the shell to tokenize the value and perform wildcard expansion on the tokens.

How do I use a file grep comparison inside a bash if/else statement?

When our server comes up we need to check a file to see how the server is configured.
We want to search for the following string inside our /etc/aws/hosts.conf file:
MYSQL_ROLE=master
Then, we want to test whether that string exists and use an if/else statement to run one of two options depending on whether the string exists or not.
What is the BASH syntax for the if statement?
if [ ????? ]; then
#do one thing
else
#do another thing
fi
From grep --help, but also see man grep:
Exit status is 0 if any line was selected, 1 otherwise;
if any error occurs and -q was not given, the exit status is 2.
if grep --quiet MYSQL_ROLE=master /etc/aws/hosts.conf; then
echo exists
else
echo not found
fi
You may want to use a more specific regex, such as ^MYSQL_ROLE=master$, to avoid that string in comments, names that merely start with "master", etc.
This works because the if takes a command and runs it, and uses the return value of that command to decide how to proceed, with zero meaning true and non-zero meaning false—the same as how other return codes are interpreted by the shell, and the opposite of a language like C.
if takes a command and checks its return value. [ is just a command.
if grep -q ...
then
....
else
....
fi
Note that, for PIPE being any command or sequence of commands, then:
if PIPE ; then
# do one thing if PIPE returned with zero status ($?=0)
else
# do another thing if PIPE returned with non-zero status ($?!=0), e.g. error
fi
For the record, [ expr ] is a shell builtin† shorthand for test expr.
Since grep returns with status 0 in case of a match, and non-zero status in case of no matches, you can use:
if grep -lq '^MYSQL_ROLE=master' ; then
# do one thing
else
# do another thing
fi
Note the use of -l which only cares about the file having at least one match (so that grep returns as soon as it finds one match, without needlessly continuing to parse the input file.)
†on some platforms [ expr ] is not a builtin, but an actual executable /bin/[ (whose last argument will be ]), which is why [ expr ] should contain blanks around the square brackets, and why it must be followed by one of the command list separators (;, &&, ||, |, &, newline)
just use bash
while read -r line
do
case "$line" in
*MYSQL_ROLE=master*)
echo "do your stuff";;
*) echo "doesn't exist";;
esac
done <"/etc/aws/hosts.conf"
Below code sample should work:
(echo "hello there" | grep -q "AAA") && [ $? -eq 0 ] && echo "hi" || echo "bye"

Resources