Please help me understand the usage of && and || in the below code
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Please help me understand the usage of && and || in the below code
Hi All,
Can someone please help me understand few things in the below code.
Code:
#!/bin/bash
# version 1.0
# Purpose: Determine if current user is root or not
is_root_user(){
[ $(id -u) -eq 0 ]
}
# invoke the function
# make decision using conditional logical operators
is_root_user && echo "You can run this script." || echo "You need to run this script as a root user."
I'm guessing [ $(id -u) -eq 0 ] is an if statement, but just wanted to make sure I understand it right. And
what is the meaning of the last statement in the code with && and || .
this kind of command:
if <command1> then <command2> else <command3>
was "translated" into:
<command1> && <command2> || <command3>
So it looks like an if/then/else, but it won't really work that way. In general command3 will only be executed if either command1 or command2 failed. command2 will be executed only if command1 was successfully completed.
Actually the second command an echo which cannot fail so in this case it really similar to an if/then/else.
see man bash, compound commands and especially:
Code:
expression1 && expression2
True if both expression1 and expression2 are true.
expression1 || expression2
True if either expression1 or expression2 is true.
The && and || operators do not evaluate expression2 if the value of expression1 is sufficient to determine the return value of the entire conditional expression.
'&&' means AND and '||' means OR and that translates into
If 'is_root_user' is true (returns 0), then 'echo "You can run this script."' otherwise (is_root_user returned not 0) 'echo "You need to run this script as a root user."'
This is a different way to write you code:
Code:
if is_root_user; then
echo "You can run this script."
else
echo "You need to run this script as a root user."
I'm guessing [ $(id -u) -eq 0 ] is an if statement, but just wanted to make sure I understand it right.
It's not an if statement, it's just a test command:
Code:
$ help [
[: [ arg... ]
Evaluate conditional expression.
This is a synonym for the "test" builtin, but the last argument must
be a literal `]', to match the opening `['.
Recommend you add a debug modification and try the script to see what comes out of it:
Code:
#!/bin/bash
# version 1.0
set -xv
# Purpose: Determine if current user is root or not
is_root_user(){
[ $(id -u) -eq 0 ]
}
# invoke the function
# make decision using conditional logical operators
is_root_user && echo "You can run this script." || echo "You need to run this script as a root user."
And by the way, what does the script do now when you run it?
In real application, there wouldn't be any use of "You can run this script" message
If the script has to be run by root, then when the id -u -eq 0 test fails, script exits with error (maybe with a message)
Code:
#!/bin/bash
# version 1.1
# Purpose: Determine if current user is root or not
is_root_user(){
[ $(id -u) -eq 0 ]
}
# Purpose: exit on error with a message
exit_error() {
echo $1 >&2
exit 1
}
is_root_user || exit_error "You need to run this script as a root user."
This concept is called, in other languages: "short-circuit" Boolean expression evaluation.
True OR anything is always True. Therefore, if the left-hand part of an OR expression is found to be True, the right-hand part does not need to be evaluated (... executed ...) at all.
Similarly, False AND anything is always False, so the right-hand part need not be executed.
(Compare this notion to bitwise logical operators, which specify that certain logical arithmetic operations should be applied to some integer quantity.)
Bash programmers use a construct like Test &&do-something in order to say, in one convenient line, that something should happen only if the Test is true. (Because, if Test is False, do-something will never be executed: it will be "short-circuited" away.)
Last edited by sundialsvcs; 10-03-2016 at 06:55 AM.
this kind of command:
if <command1> then <command2> else <command3>
was "translated" into:
<command1> && <command2> || <command3>
why "misuse"? or maybe pan64 meant it in a positive way?
================================
one thing that was important for me to understand these: && binds stronger than ||, like in maths multiplication/division binds stronger than addition/substraction:
<command1> && <command2> || <command3>
is the same as
( <command1> && <command2> ) || <command3>
but not the same as
<command1> && ( <command2> || <command3> )
================================
and it is also important to understand that the shell works through these constructs left to right, just like you write them. that's why it works.
you explained it very well, but to make it even better:
if <command1> then <command2> else <command3>
the execution of <command3> depends only on the result of <command1>
<command1> && <command2> || <command3>
the execution of <command3> may depend on both <command1> and <command2>.
In this construct there is a way to run all the three commands.
Therefore using a && b || c to implement an if/then/else is incorrect, but in some cases it looks very similar (especially when b cannot fail - like an echo).
Additionally you can try a || b && c which will lead to even more confusion/fun
Personally, if I had to do anything involving more than one operator, I would use if..then..else if only to make my intentions perfectly clear.
As it happens, I rarely use operators. Again, for this same reason. It doesn't matter so much that my statement is clear to the computer. What matters is that it is clear, "at a glance," to people.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.