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

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.

Related

tail | grep -q always returning true

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 ...).

Bash if statement not working properly

I have a bash statement to test a command line argument. If the argument passed to the script is "clean", then the script removes all .o files. Otherwise, it builds a program. However, not matter what is passed (if anything), the script still thinks that the argument "clean" is being passed.
#!/bin/bash
if test "`whoami`" != "root" ; then
echo "You must be logged in as root to build (for loopback mounting)"
echo "Enter 'su' or 'sudo bash' to switch to root"
exit
fi
ARG=$1
if [ $ARG == "clean" ] ; then
echo ">>> cleaning up object files..."
rm -r src/*.o
echo ">>> done. "
echo ">>> Press enter to continue..."
read
else
#Builds program
fi
Answer for first version of question
In bash, spaces are important. Replace:
[ $ARG=="clean" ]
With:
[ "$ARG" = "clean" ]
bash interprets $ARG=="clean" as a single-string. If a single-string is placed in a test statement, test returns false if the string is empty and true if it is non-empty. $ARG=="clean" will never be empty. Thus [ $ARG=="clean" ] will always return true.
Second, $ARG should be quoted. Otherwise, if it is empty, then the statement reduces to `[ == "clean" ] which is an error ("unary operator expected").
Third, it is best practices to use lower or mixed case for your local variables. The system uses upper-case shell variables and you don't want to accidentally overwrite one of them.
Lastly, with [...], the POSIX operator for equal, in the string sense, is =. Bash will accept either = or == but = is more portable.
first:
Every string must double quoted or will error absent argument.
second:
for string used only = or != not a == and also -n and -z commands.
third:
you may combine conditions by -a and -o commands but newer used enclose in () yous conditions so not to get error. Logical operators acts through operators presidence, fist calculate -o operator and then -a! For example
[ -n "$1" -a $1 = '-h' -o $1 = '--help' ] && { usage; exit 0; }
will work when passed to script at least 1 argument and is -h or --help. All spaces must be!!! Bush do short cycle logical evaluations. So don't trouble for case when $1 don't exist in second condition because of result of this expression is determined in first one. next don't calculate in this case. But if your argument may contains space symbols you need it double quote. You must do it also in command line too! Else you get error in script or split your arguments in two or more parts.
Operator == isn't used in test. For numbers(not siring) used -eq or -ne commands. See man 1 test for full descriptions. test EXPRESSION... equivalent of [ EXPRESSIONS... ]. More shirt form of test.

What does the operator != mean in a shell script?

In this i have an exclamation mark in my second if statement why is this used.
#!/bin/bash
name=$1
if [ "$name" = "" ]
then echo -n "Enter a name to search for: "
read name
fi
grep -i cheryl ~uli101/uli101/phonebook
grep -i $name ~uli101/uli101/phonebook
if [ "$?" != "0" ]
then echo -n "Name '$name' not in directory "
fi
The special shell parameter $? contains the exit code from the last command run. Every command you run from the shell reports a numeric status back to the shell when it finishes running; in general, a value of 0 means the command succeeded, and a nonzero value means it failed.
The grep command searches a file for lines matching a pattern. If it finds any matching lines, it prints them out, but it also exits with status 0 if it found at least one match, and a nonzero status if it didn't find any.
The syntax [ expression ] is a command that evaluates the given expression (usually a comparison of some sort) to see if it's true or not. Really, it's just another shell command, that exits with status 0 if the expression is true and 1 if it's false; the if construct in the shell decides what to do based on the value of $?.
And the != operator means 'is not equal to', so [ $? != 0 ] is checking to see if $? is not equal to zero.
Putting all that together, the above code checks to see if the grep found a match or not.
The origin of != is the C family of programming languages, in which the exclamation point generally means "not". In bash, a ! at the start of a command will invert the exit status of the command, turning nonzero values to zero and zeroes to one. So you could also "move the exclamation point" and rewrite the above expression like this:
if ! [ $? == 0 ]
However, since if itself operates based on exit status, all of the above code is doing extra work. You can skip the middleman and just test grep directly:
if ! grep -i "$name" ~uli101/uli101/phonebook; then
echo "Name '$name' not in directory."
fi
Note that I put double quotes around $name, which prevents any spaces in the value from separating it into multiple arguments to grep.
[ "$?" != "0" ] means "$? not equal to 0". See the full list of Bash test operators here.
Note that $? will be set to 0 if grep finds a match, and 1 otherwise.

multiple if condition in unix

I am trying to run the below logic
if [-f $file] && [$variable -lt 1] ; then
some logic
else
print "This is wrong"
fi
It fails with the following error
MyScipt.ksh[10]: [-f: not found
Where 10th line is the if condition , I have put in .
I have also tried
if [-f $file && $variable -lt 1] ; then
which gives the same error.
I know this is a syntax mistake somehwere , but I am not sure , what is the correct syntax when I am using multiple conditions with && in a if block
[ is not an operator, it's the name of a program (or a builtin, sometimes). Use type [ to check. Regardless, you need to put a space after it so that the command line parser knows what to do:
if [ -f $file ]
The && operator might not do what you want in this case, either. You should probably read the bash(1) documentation. In this specific case, it seems like what you want is:
if [ -f $file -a $variable -lt 1 ]
Or in more modern bash syntax:
if [[ -f $file && $variable -lt 1 ]]
The [ syntax is secretly a program!
$ type [
[ is a shell builtin
$ ls -l $(which [)
-rwxr-xr-x 1 root root 35264 Nov 19 16:25 /usr/bin/[
Because of the way the shell parses (technically "lexes") your command line, it sees this:
if - keyword
[-f - the program [-f
$file] - A string argument to the [-f program, made by the value of $file and ]. If $file was "asdf", then this would be asdf]
And so forth, down your command. What you need to do is include spaces, which the shell uses to separate the different parts (tokens) of your command:
if [ -f "$file" ]; then
Now [ stands on its own, and can be recognized as a command/program. Also, ] stands on its own as an argument to [, otherwise [ will complain. A couple more notes about this:
You don't need to put a space before or after ;, because that is a special separator that the shell recognizes.
You should always "double quote" $variables because they get expanded before the shell does the lexing. This means that if an unquoted variable contains a space, the shell will see the value as separate tokens, instead of one string.
Using && in an if-test like that isn't the usual way to do it. [ (also known as test) understands -a to mean "and," so this does what you intended:
if [ -f "$file" -a "$variable" -lt 1 ]; then
Use -a in an if block to represent AND.
Note the space preceding the -f option.
if [ -f $file -a $variable -lt 1] ; then
some logic
else
print "This is wrong"
fi

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