13-B.4: Shell Operators
- Page ID
- 43190
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)Operators in Shell Scripts
There are five basic operators in bash/shell scripting:
- Arithmetic Operators
- Relational Operators
- Boolean Operators
- Bitwise Operators
- File Test Operators
- Arithmetic Operators: These operators are used to perform normal arithmetics/mathematical operations. There are seven arithmetic operators:
- Addition (+): Binary operation used to add two operands.
- Subtraction (-): Binary operation used to subtract two operands.
- Multiplication (*): Binary operation used to multiply two operands.
- Division (/): Binary operation used to divide two operands.
- Modulus (%): Binary operation used to find remainder of two operands.
- Increment Operator (++): Unary operator used to increase the value of operand by one.
- Decrement Operator (–): Unary operator used to decrease the value of a operand by one
- Relational Operators: Relational operators are those operators which define the relation between two operands. They give either true or false depending upon the relation. There are six types:
- ‘==’ Operator: Double equal to operator compares the two operands. It returns true if they are equal otherwise returns false.
- ‘!=’ Operator: Not equal to operator returns true if the two operands are not equal otherwise it returns false.
- ‘<' Operator: Less than operator returns true if first operand is less than second operand otherwise returns false.
- ‘<=' Operator: Less than or equal to operator returns true if first operand is less than or equal to second operand otherwise returns false
- ‘>’ Operator: Greater than operator returns true if the first operand is greater than the second operand otherwise returns false.
- ‘>=’ Operator: Greater than or equal to operator returns true if first operand is greater than or equal to second operand otherwise returns false.
- Logical Operators: They are also known as boolean operators. These are used to perform logical operations. There are three types:
- Logical AND (&&): This is a binary operator, which returns true if both the operands are true otherwise returns false.
- Logical OR (||): This is a binary operator, which returns true if either of the operands is true or both the operands are true and returns false if none of them is false.
- Not Equal to (!): This is a unary operator which returns true if the operand is false and returns false if the operand is true.
- Bitwise Operators: A bitwise operator is an operator used to perform bitwise operations on bit patterns. There are six types.
- Bitwise And (&): Bitwise & operator performs binary AND operation bit by bit on the operands.
- Bitwise OR (|): Bitwise | operator performs binary OR operation bit by bit on the operands.
- Bitwise XOR (^): Bitwise ^ operator performs binary XOR operation bit by bit on the operands.
- Bitwise compliment (~): Bitwise ~ operator performs binary NOT operation bit by bit on the operand.
- Left Shift (<<): This operator shifts the bits of the left operand to left by number of times specified by right operand.
- Right Shift (>>): This operator shifts the bits of the left operand to right by number of times specified by right operand.
- File Test Operator: These operators are used to test a particular property of a file.
- -b operator: This operator checks whether a file is a block special file or not. It returns true if the file is a block special file, otherwise returns false.
- -c operator: This operator checks whether a file is a character special file or not. It returns true if it is a character special file otherwise returns false.
- -d operator: This operator checks if the given directory exists or not. If it exists then operators returns true otherwise returns false.
- -e operator: This operator checks whether the given file exists or not. If it exists this operator returns true otherwise returns false.
- -r operator: This operator checks whether the given file has read access or not. If it has read access then it returns true otherwise returns false.
- -w operator: This operator checks whether the given file has write access or not. If it has write then it returns true otherwise returns false.
- -x operator: This operator checks whether the given file has execute access or not. If it has execute access then it returns true otherwise returns false.
- -s operator: This operator checks the size of the given file. If the size of given file is greater than 0 then it returns true otherwise it returns false.
Some Things About Operations
Variables are assigned values and can be used to refer to those values in CLI programs and scripts. The value of a variable is set using its name but not preceded by a $ sign. The assignment VAR=10 sets the value of the variable VAR to 10. To print the value of the variable, you can use the statement echo $VAR. Start with text (i.e., non-numeric) variables.
Bash variables become part of the shell environment until they are unset.
Check the initial value of a variable that has not been assigned; it should be null. Then assign a value to the variable and print it to verify its value. You can do all of this in a single CLI program: (there are multiple commands on a single line - separated by a ; - this is totally okay to enter commands this way).
pbmac@pbmac-server $ echo $MyVar ; MyVar="Hello World" ; echo $MyVar ;
Hello World
pbmac@pbmac-server $
Note: The syntax of variable assignment is very strict. There must be no spaces on either side of the equal (=) sign in the assignment statement.
The empty line indicates that the initial value of MyVar is null. Changing and setting the value of a variable is done the same way. This example shows both the original and the new value.
As mentioned, Bash can perform integer arithmetic calculations, which is useful for calculating a reference to the location of an element in an array or doing simple math problems. It is not suitable for scientific computing or anything that requires decimals, such as financial calculations. There are much better tools for those types of calculations.
Here's a simple calculation: (NOTICE that arithmetic calculations are enclosed in DOUBLE parenthesis - also that the $ character is OUTSIDE the parenthesis).
pbmac@pbmac-server $ Var1="7" ; Var2="9" ; echo "Result = $((Var1*Var2))"
Result = 63
What happens when you perform a math operation that results in a floating-point number?
pbmac@pbmac-server $ Var1="7" ; Var2="9" ; echo "Result = $((Var1/Var2))"
Result = 0
pbmac@pbmac-server $ Var1="7" ; Var2="9" ; echo "Result = $((Var2/Var1))"
Result = 1
The result is the nearest integer. Notice that the calculation was performed as part of the echo statement. The math is performed before the enclosing echo command due to the Bash order of precedence. For details see the Bash man page and search "precedence."
Here are some simple examples of logical operations. The first instance sets the variable $X to 1, then tests to see if $X is equal to 1. In the second instance, X is set to 0, so the comparison is not true.
pbmac@pbmac-server $ X=1 ; if [ $X -eq 1 ] ; then echo "X equals 1" ; else echo "X does not equal 1" ; fi
X equals 1
pbmac@pbmac-server $ X=0 ; if [ $X -eq 1 ] ; then echo "X equals 1" ; else echo "X does not equal 1" ; fi
X does not equal 1
Some things to notice in these examples: 1) when using square brackets - [ ] - there MUST be a space after the left bracket and before the right bracket; 2) when this command is entered on the command line, the semi-colon is required; 3) when using an if statement you MUST close it with a fi statement; 4) if this command is in a text file and is broken up into multiple lines, the semi-colon is NOT required; and 5) the fi to end the if statement: (NOTICE the first line, often referred to as the "shebang" line).
#!/bin/bash
if [ $X -eq 1 ]
then
echo "X equals 1"
else
echo "X does not equal 1"
fi
The control operator syntax using some flow control takes this general form when the && and || control operators are used:
preceding commands ; command1 && command2 || command3 ; following commands
This syntax can be stated like so: "If command1 exits with a return code of 0, then execute command2, otherwise execute command3." Try it:
pbmac@pbmac-server $ Dir=~/testdir ; mkdir $Dir && cd $Dir || echo "$Dir was not created."
The control operator syntax, like command1 && command2, works because every command sends a return code (RC) to the shell that indicates if it completed successfully or whether there was some type of failure during execution. By convention, an RC of zero (0) indicates success, and any positive number indicates some type of failure.
Again, if we put this command line into a text file we have a few changes to the syntax:
#!/bin/bash
Dir=~/testdir
if [ "mkdir $Dir" ] && [ "cd $Dir" ]
then
echo "$Dir was not created."
fi
The script has 1) the shebang line; 2) notice the content within the [ ] is enclosed in quotations...this is required, otherwise an error is generated; 3) and again, the fi to end the if.
Adapted from:
"Basic Operators in Shell Scripting" by DrRoot_, Geeks for Geeks is licensed under CC BY-SA 4.0
"How to program with Bash: Syntax and tools" by David Both, OpenSource.com is licensed under CC BY-SA 4.0
"How to program with Bash: Logical operators and shell expansions" by David Both, OpenSource.com is licensed under CC BY-SA 4.0
"How to program with Bash: Loops" by David Both, OpenSource.com is licensed under CC BY-SA 4.0