Topic3
CONDITIONALS
3/12/2021
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 $?
$ $ 1 $ $ 0
cat someFileThatDoesNotExist.txt echo $?
ls
echo $?
# “Failure”
# “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
1
The test command
$ $ 1 $ $ 0
[ 10 –lt 5 ] echo $?
[ 10 –gt 5 ] echo $?
# “False”, “Failure”
# “True”, “Success”
test operators
TOPIC 3 – CONDITIONALS 3
3/12/2021
$ $ 1 $ $ 0
test 10 –lt 5 echo $?
# “False”, “Failure” test 10 –gt 5
echo $?
# “True”, “Success”
Another syntax for the test command:
Don’t forget the space after [ and before ]
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
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
*Note: man test will show other operators.
TOPIC 3 – CONDITIONALS 4
2
if/else
if [ condition ]; then commands
fi
if [ condition ]; then commands1
elif [ condition ]; then commands2
else
commands3
# basic if
# if / else if / else
fi
◦ The [ ] syntax is actually shorthand for a shell command called “test”
(Try: “man test”)
◦ thereMUSTbespacesasshown: ifspace[spacecondition space ]
◦ include the semi-colon after ] (or put “then” on the next line)
3/12/2021
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
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
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
3/12/2021
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
TOPIC 3 – CONDITIONALS 8
4
if statement
if command
then
statements
fi
statements are executed only if command succeeds, i.e. has return status “0”
3/12/2021
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
9
Topic 3 – Conditionals
10
Topic 3 – Conditionals
5
The simple if statement
if [ condition ]; then
statements
fi
executes the statements only if condition is true
3/12/2021
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
11
Topic 3 – Conditionals
12
Topic 3 – Conditionals
6
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
Relational Operators
3/12/2021
13
Topic 3 – Conditionals
Meaning
Greater than
Greater than or equal
Less than
Less than or equal
Equal
Not equal
str1 is less than str2
str1 is greater str2
String length is greater than zero
String length is zero
Numeric
-gt
-ge
-lt
-le
-eg
-ne
String
= or ==
!=
str1 < str2
str1 > str2
-n str
-z str
TOPIC 3 – CONDITIONALS 14
7
Compound logical expressions
!
&& ||
not
and or
and, or
must be enclosed within
[[ ]]
3/12/2021
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
15
Topic 3 – Conditionals
16
Topic 3 – Conditionals
8
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
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
3/12/2021
17
Topic 3 – Conditionals
18
Topic 3 – Conditionals
9
File Testing
-d file -f file -r file -w file -x file -s file
Meaning
True if ‘file’ is a directory
True if ‘file’ is an ordinary file True if ‘file’ is readable
True if ‘file’ is writable
True if ‘file’ is executable
True if length of ‘file’ is nonzero
3/12/2021
Example: File Testing
#!/bin/bash
echo “Enter a filename: ”
read filename
if [ ! –r “$filename” ]
then
echo “File is not read-able”
exit 1 fi
19
Topic 3 – Conditionals
20
Topic 3 – Conditionals
10
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
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
3/12/2021
21
Topic 3 – Conditionals
22
Topic 3 – Conditionals
11
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
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
3/12/2021
23
Topic 3 – Conditionals
24
Topic 3 – Conditionals
12
case pattern
checked against word for match may also contain:
*
?
[…]
[:class:]
multiple patterns can be listed via: |
Example 1: The case Statement
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
25
Topic 3 – Conditionals
3/12/2021
#!/bin/bash
echo “Enter
echo “Enter
echo “Enter
read -p “Enter your choice: ” reply case $reply in
Y to see all files including hidden files” N to see all non-hidden files”
q to quit”
26
Topic 3 – Conditionals
13
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
3/12/2021
27
Topic 3 – Conditionals
14