Bash Shell Variables and Loops


Variables

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
OperatorName
==Is equal to
!=Is not equal to
-eqAlternative form of “is equal to”
-neAlternative form of “is not equal to”
-gtGreater than
-ltLess than
-geGreater than or equal to
-leLess 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/bash
mynum=100
echo "Enter a number"
read num1
if [ $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.

while :
do
	something here