Topic 4
3/12/2021
1
Topic 3
CONDITIONALS
Exit Status
Every Linux command returns an integer code when it finishes, called its “exit status”
◦ 0 usually* denotes success, or an OK exit status
◦ Anything other than 0 (1 to 255) usually denotes an error
You can return an exit status explicitly using the exit statement
You can check the status of the last command executed in the variable $?
$ cat someFileThatDoesNotExist.txt
$ echo $?
1 # “Failure”
$ ls
$ echo $?
0 # “Success”
* One example exception: diff returns “0” for no differences,
“1” if differences found, “2” for an error such as invalid filename argument
TOPIC 3 – CONDITIONALS 2
3/12/2021
2
The test command
$ test 10 –lt 5
$ echo $?
1 # “False”, “Failure”
$ test 10 –gt 5
$ echo $?
0 # “True”, “Success”
Another syntax for the test command:
Don’t forget the space after [ and before ]
$ [ 10 –lt 5 ]
$ echo $?
1 # “False”, “Failure”
$ [ 10 –gt 5 ]
$ echo $?
0 # “True”, “Success”
TOPIC 3 – CONDITIONALS 3
test operators
if [ $USER = “lancer14″ ]; then
echo ‘Go Lancers!’
fi
LOGINS=$(w -h | wc -l)
if [ $LOGINS -gt 10 ]; then
echo ‘attu is very busy right now!’
fi
comparison operator description
=, !=, \<, \> compares two string variables
-z, -n tests if a string is empty (zero-length) or not empty
(nonzero-length)
-lt, -le, -eq,
-gt, -ge, -ne
compares numbers; equivalent to Java’s
<, <=, ==, >, >=, !=
-e, -f, -d tests whether a given file or directory exists
-r, -w, -x tests whether a file exists and is readable/writable/executable
*Note: man test will show other operators.
TOPIC 3 – CONDITIONALS 4
3/12/2021
3
if/else
if [ condition ]; then # basic if
commands
fi
if [ condition ]; then # if / else if / else
commands1
elif [ condition ]; then
commands2
else
commands3
fi
◦ The [ ] syntax is actually shorthand for a shell command called “test”
(Try: “man test”)
◦ there MUST be spaces as shown:
if space [ space condition space ]
◦ include the semi-colon after ] (or put “then” on the next line)
TOPIC 3 – CONDITIONALS 5
#!/bin/bash
read -p “Enter a number : ” n
if [ $n -gt 0 ]; then
echo “$n is a positive.”
elif [ $n -lt 0 ]
then
echo “$n is a negative.”
elif [ $n -eq 0 ]
then
echo “$n is zero number.”
else
echo “Oops! $n is not a number.”
TOPIC 3 – CONDITIONALS 6
3/12/2021
4
More if testing
# alert user if running >= 10 processes when
# attu is busy (>= 5 users logged in)
LOGINS=$(w -h | wc -l)
PROCESSES=$(ps -u $USER | wc -l)
if [ $LOGINS -ge 5 -a $PROCESSES -gt 10 ]; then
echo “Quit hogging the server!”
fi
compound comparison operators description
if [ expr1 -a expr2 ]; then …
if [ expr1 ] && [ expr2 ]; then …
and
if [ expr1 -o expr2 ]; then …
if [ expr1 ] || [ expr2 ]; then …
or
if [ ! expr ]; then … not
TOPIC 3 – CONDITIONALS 7
Common errors
[: -eq: unary operator expected
◦ you used an undefined variable in an if test
[: too many arguments
◦ you tried to use a variable with a large, complex value (such as multi-line output from a
program) as though it were a simple int or string
let: syntax error: operand expected (error token is ” “)
◦ you used an undefined variable in a let mathematical expression
TOPIC 3 – CONDITIONALS 8
3/12/2021
5
if statement
if command
then
statements
fi
statements are executed only if command succeeds, i.e. has return
status “0”
9
Topic 3 –
Conditionals
test command
Syntax:
test expression
[ expression ]
evaluates ‘expression’ and returns true or false
Example:
if test –w “$1”
then
echo “file $1 is write-able”
fi
10
Topic 3 –
Conditionals
3/12/2021
6
The simple if statement
if [ condition ]; then
statements
fi
executes the statements only if condition is true
11
Topic 3 –
Conditionals
The if-then-else statement
if [ condition ]; then
statements-1
else
statements-2
fi
executes statements-1 if condition is true
executes statements-2 if condition is false
12
Topic 3 –
Conditionals
3/12/2021
7
The if…statement
if [ condition ]; then
statements
elif [ condition ]; then
statement
else
statements
fi
The word elif stands for “else if”
It is part of the if statement and cannot be used by itself
13
Topic 3 –
Conditionals
TOPIC 3 – CONDITIONALS 14
Relational Operators
Meaning Numeric String
Greater than -gt
Greater than or equal -ge
Less than -lt
Less than or equal -le
Equal -eg = or ==
Not equal -ne !=
str1 is less than str2 str1 < str2 str1 is greater str2 str1 > str2
String length is greater than zero -n str
String length is zero -z str
3/12/2021
8
Compound logical expressions
! not
&& and
|| or
15
Topic 3 –
Conditionals
and, or
must be enclosed within
[[ ]]
Example: Using the ! Operator
#!/bin/bash
read -p “Enter years of work: ” Years
if [ ! “$Years” -lt 20 ]; then
echo “You can retire now.”
else
echo “You need 20+ years to retire”
fi
16
Topic 3 –
Conditionals
3/12/2021
9
Example: Using the && Operator
#!/bin/bash
Bonus=500
read -p “Enter Status: ” Status
read -p “Enter Shift: ” Shift
if [[ “$Status” = “H” && “$Shift” = 3 ]]
then
echo “shift $Shift gets \$$Bonus bonus”
else
echo “only hourly workers in”
echo “shift 3 get a bonus”
fi
17
Topic 3 –
Conditionals
Example: Using the || Operator
#!/bin/bash
read -p “Enter calls handled:” CHandle
read -p “Enter calls closed: ” CClose
if [[ “$CHandle” -gt 150 || “$CClose” -gt 50 ]]
then
echo “You are entitled to a bonus”
else
echo “You get a bonus if the calls”
echo “handled exceeds 150 or”
echo “calls closed exceeds 50”
fi
18
Topic 3 –
Conditionals
3/12/2021
10
File Testing
Meaning
-d file True if ‘file’ is a directory
-f file True if ‘file’ is an ordinary file
-r file True if ‘file’ is readable
-w file True if ‘file’ is writable
-x file True if ‘file’ is executable
-s file True if length of ‘file’ is nonzero
19
Topic 3 –
Conditionals
Example: File Testing
#!/bin/bash
echo “Enter a filename: ”
read filename
if [ ! –r “$filename” ]
then
echo “File is not read-able”
exit 1
fi
20
Topic 3 –
Conditionals
3/12/2021
11
Example: File Testing
#! /bin/bash
if [ $# -lt 1 ]; then
echo “Usage: filetest filename”
exit 1
fi
if [[ ! -f “$1” || ! -r “$1” || ! -w “$1” ]]
then
echo “File $1 is not accessible”
exit 1
fi
21
Topic 3 –
Conditionals
Example: if… Statement
# The following THREE if-conditions produce the same result
* DOUBLE SQUARE BRACKETS
read -p “Do you want to continue?” reply
if [[ $reply = “y” ]]; then
echo “You entered ” $reply
fi
* SINGLE SQUARE BRACKETS
read -p “Do you want to continue?” reply
if [ $reply = “y” ]; then
echo “You entered ” $reply
fi
* “TEST” COMMAND
read -p “Do you want to continue?” reply
if test $reply = “y”; then
echo “You entered ” $reply
fi
22
Topic 3 –
Conditionals
3/12/2021
12
Example: if..elif… Statement
#!/bin/bash
read -p “Enter Income Amount: ” Income
read -p “Enter Expenses Amount: ” Expense
let Net=$Income-$Expense
if [ “$Net” -eq “0” ]; then
echo “Income and Expenses are equal – breakeven.”
elif [ “$Net” -gt “0” ]; then
echo “Profit of: ” $Net
else
echo “Loss of: ” $Net
fi
23
Topic 3 –
Conditionals
The case Statement
use the case statement for a decision that is based on multiple choices
Syntax:
case word in
pattern1) command-list1
;;
pattern2) command-list2
;;
patternN) command-listN
;;
esac
24
Topic 3 –
Conditionals
3/12/2021
13
case pattern
checked against word for match
may also contain:
*
?
[ … ]
[:class:]
multiple patterns can be listed via:
|
25
Topic 3 –
Conditionals
Example 1: The case Statement
#!/bin/bash
echo “Enter Y to see all files including hidden files”
echo “Enter N to see all non-hidden files”
echo “Enter q to quit”
read -p “Enter your choice: ” reply
case $reply in
Y|YES) echo “Displaying all (really…) files”
ls -a ;;
N|NO) echo “Display all non-hidden files…”
ls ;;
Q) exit 0 ;;
*) echo “Invalid choice!”; exit 1 ;;
esac
26
Topic 3 –
Conditionals
3/12/2021
14
Example 2: The case Statement
#!/bin/bash
ChildRate=3
AdultRate=10
SeniorRate=7
read -p “Enter your age: ” age
case $age in
[1-9]|[1][0-2]) # child, if age 12 and younger
echo “your rate is” ‘$'”$ChildRate.00″ ;;
# adult, if age is between 13 and 59 inclusive
[1][3-9]|[2-5][0-9])
echo “your rate is” ‘$'”$AdultRate.00″ ;;
[6-9][0-9]) # senior, if age is 60+
echo “your rate is” ‘$'”$SeniorRate.00″ ;;
esac
27
Topic 3 –
Conditionals