Variables hold reusable values and are foundational to the use of scripts
export command sets the variable within the current shell session
set a variable: VARIABLE=value
call a variable: $VARIABLE
can set a variable dynamically with read
e.g., read VARIABLE
gets user input and stores in VARIABLE
Arithmetic
Shells incorporate a few special conventions to perform arithmetic
e.g., expr command is needed to perform arithmetic
arithmetic operations performed with variables must be contain in back ticks (``)
allow the variables to be evaluated
e.g., sum=`expr $num1 $num2`
Boolean Operators
Boolean operators are used to perform comparisons.
e.g., var1 == var2
Operator
Name
==
Is equal to
!=
Is not equal to
-eq
Alternative form of “is equal to”
-ne
Alternative form of “is not equal to”
-gt
Greater than
-lt
Less than
-ge
Greater than or equal to
-le
Less than or equal to
If/Else Statements
Comparisons are used to create decision branches which help steer the direction of the script’s commands
If/Else statements help identify a course of action based on a set of comparisons
boolean comparisons are contained within square brackets
there are spaces between the brackets and the comparison statement
e.g., [ $num1 -gt $num2 ]
Example
#!/bin/bashmynum=100echo "Enter a number"read num1if [ $num1 -gt $mynum ]; then echo "Your number is bigger"elif [ $num1 -lt $mynum ]; then echo "Your number is smaller"else echo "We picked the same number!"fi
While Loops
A while loop will continue processing a series of commands until a predetermined condition is met.