Serious Shell Programming
  • Introduction
  • Acknowledgements
  • Basics
    • Strings
      • Single-Quotes
      • Double-Quotes
      • Unquoted Strings
      • Compound Strings
    • Here Documents
      • Here Doc
      • Indented Here Doc
      • Literal Here Doc
      • In-Memory Here Doc
    • Conditionals
      • Built-in test
      • Parameter Conditionals
      • Parameter test
    • Regex
      • grep
      • awk
      • pcre
    • Control Flow
      • Binary Operators
      • if-elif-else
      • case Statement
      • for Loop
      • while Loop
      • Functions
  • shellcheck
    • Introduction
    • Bad Advice
  • Style
    • awk
    • case
    • Redirection
    • Comments
    • trap
  • String Functions
    • substr
    • sprintf
    • replace
    • replaceall
    • replacestart
    • replaceend
    • fnmatch
  • awk
    • Pre-declaring Arrays
    • Sorting Arrays
  • Know Your limits
    • Arguments
    • Environment Variables
    • Solutions
Powered by GitBook
On this page

Was this helpful?

  1. Basics
  2. Control Flow

Binary Operators

The && and || operators each take two operands (making them binary). We will refer to the operand appearing on the left of the operator as the lvalue and the operand on the right the rvalue.

The exit status of the lvalue command determines, depending on which operator you use, if the rvalue command is executed.

lvalue exit status

Operator

rvalue command

zero (SUCCESS)

&&

Executed

zero

∣∣

Not executed

non-zero (FAILURE)

&&

Not Executed

non-zero

∣∣

Executed

The && operator acts as a logical AND between two commands and the || operator acts as a logical OR.

Any command, group of commands, or sub-shell can be used as an operand. Below are some examples:

1 #!/bin/sh
2 [ -e /proc/cmdline ] || {
3     echo "/proc/cmdline: No such file or directory"
4     exit 1
5 }
6 { cat /etc/redhat-release && ls -l /dev/sda; } || exit 1
7 year=$( date +%Y ) || year=1979

Lines 2-5 demonstrate a multi-line rvalue grouped by braces.

Line 6 demonstrates an lvalue grouped by braces.

Line 7 demonstrates that an assignment lvalue. The exit status of an assignment is that of the last command executed in the sub-shell (date +%Y). If executing date +%Y results in anything but success we would assign a default year of 1979.

PreviousControl FlowNextif-elif-else

Last updated 5 years ago

Was this helpful?