LinuxQuestions.org
Visit Jeremy's Blog.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 09-29-2016, 10:02 AM   #1
new_user3085
LQ Newbie
 
Registered: Sep 2016
Posts: 21

Rep: Reputation: Disabled
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 || .

Thanks in advance.
 
Old 09-29-2016, 10:50 AM   #2
pan64
LQ Addict
 
Registered: Mar 2012
Location: Hungary
Distribution: debian/ubuntu/suse ...
Posts: 21,840

Rep: Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308
that is a tipical misuse.
Code:
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.
 
Old 09-29-2016, 10:57 AM   #3
robertjinx
Member
 
Registered: Oct 2007
Location: Prague, CZ
Distribution: RedHat / CentOS / Ubuntu / SUSE / Debian
Posts: 749

Rep: Reputation: 73
'&&' 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."
 
Old 09-29-2016, 11:20 AM   #4
ntubski
Senior Member
 
Registered: Nov 2005
Distribution: Debian, Arch
Posts: 3,780

Rep: Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081
Quote:
Originally Posted by new_user3085 View Post
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 `['.
So you could also write
Code:
test ($id -u) -eq 0
 
Old 09-29-2016, 02:00 PM   #5
rtmistler
Moderator
 
Registered: Mar 2011
Location: USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 9,882
Blog Entries: 13

Rep: Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930
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?
 
Old 09-29-2016, 05:32 PM   #6
keefaz
LQ Guru
 
Registered: Mar 2004
Distribution: Slackware
Posts: 6,552

Rep: Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872
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."

Last edited by keefaz; 09-29-2016 at 05:34 PM.
 
Old 09-29-2016, 11:23 PM   #7
NevemTeve
Senior Member
 
Registered: Oct 2011
Location: Budapest
Distribution: Debian/GNU/Linux, AIX
Posts: 4,862
Blog Entries: 1

Rep: Reputation: 1869Reputation: 1869Reputation: 1869Reputation: 1869Reputation: 1869Reputation: 1869Reputation: 1869Reputation: 1869Reputation: 1869Reputation: 1869Reputation: 1869
Note: the opposite of this check is also possible:

Code:
if [ $(id -u) -eq 0 ]; then
    echo "I should run as 'oracle', not as 'root'"
    exec su - oracle -c "$0 $@"
    exit
fi
... start listener ...
 
Old 09-30-2016, 10:52 AM   #8
Habitual
LQ Veteran
 
Registered: Jan 2011
Location: Abingdon, VA
Distribution: Catalina
Posts: 9,374
Blog Entries: 37

Rep: Reputation: Disabled
Code:
man test
or
Code:
man bash
^CONDITIONAL EXPRESSIONS
 
Old 10-03-2016, 06:52 AM   #9
sundialsvcs
LQ Guru
 
Registered: Feb 2004
Location: SE Tennessee, USA
Distribution: Gentoo, LFS
Posts: 10,659
Blog Entries: 4

Rep: Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940
FYI:

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.
 
Old 10-05-2016, 12:23 AM   #10
ondoho
LQ Addict
 
Registered: Dec 2013
Posts: 19,872
Blog Entries: 12

Rep: Reputation: 6053Reputation: 6053Reputation: 6053Reputation: 6053Reputation: 6053Reputation: 6053Reputation: 6053Reputation: 6053Reputation: 6053Reputation: 6053Reputation: 6053
Quote:
Originally Posted by pan64 View Post
that is a tipical misuse.
Code:
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.

this:

echo "You can run this script." && is_root_user

wouldn't make any sense at all.

Last edited by ondoho; 10-05-2016 at 12:25 AM.
 
Old 10-05-2016, 12:47 AM   #11
pan64
LQ Addict
 
Registered: Mar 2012
Location: Hungary
Distribution: debian/ubuntu/suse ...
Posts: 21,840

Rep: Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308
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

Last edited by pan64; 10-05-2016 at 01:49 AM.
 
Old 10-05-2016, 09:36 AM   #12
sundialsvcs
LQ Guru
 
Registered: Feb 2004
Location: SE Tennessee, USA
Distribution: Gentoo, LFS
Posts: 10,659
Blog Entries: 4

Rep: Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940Reputation: 3940
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.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
LXer: RDO Liberty Set up for three Nodes Controller&Network&Compute (ML2&OVS&VXLAN) on CentOS 7.1 LXer Syndicated Linux News 0 10-23-2015 03:50 AM
LXer: Power & Memory Usage Of GNOME, KDE, LXDE & Xfce LXer Syndicated Linux News 0 03-08-2010 07:12 PM
AOL UK && BT Voyager 100 && Slackware 10.2 && RP-PPPoE pitt0071 Linux - Networking 3 01-17-2006 06:10 AM
Japanese canna won't work : Warning: &#12363;&#12394;&#28450;&#23383;&#22793;&am OrganicOrange84 Debian 3 06-30-2005 02:28 PM
Ph&#7909;c h&#7891;i d&#7919; li&#7879;u b&#7883; m&#7845;t???, c&#7913; pollsite General 1 06-27-2005 12:39 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 04:45 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration