Introduction to Unix (CA263) Decisions, Decisions By Tariq Ibn Aziz

Download Report

Transcript Introduction to Unix (CA263) Decisions, Decisions By Tariq Ibn Aziz

Introduction to Unix (CA263)
Decisions, Decisions
By
Tariq Ibn Aziz
Dammam Community College
Objectives
• In this lecture you will learn
–
–
–
–
–
–
–
Statements that is present in almost all languages
Exit status
The $? Variable
The test command
File operators
The Logical Negation Operator !
The Logical AND Operator -a
Objectives
• In this lecture you will learn
– Parentheses
– The Logical OR Operator –o
– The else Construct
– The exit Command
– The elif Construct
– The case Command
– The Null Command
– The && and || Construct
Exit status
• Whenever any program complete execution
under UNIX system, it returns an exit status
back to the system.
• This status is a number that usually indicates
whether the program successfully ran or not.
• The exit status of zero indicates that a program
ran successfully, and nonzero to indicate that it
failed.
• Example: cp command return nonzero if the
copy fails for some reason, or if arguments are
not specified correctly.
Exit status Example
• In a pipeline, the exit status is that of the
last command in the pipe. So in
Who | grep fred
• The exit status of the grep is used by the
shell as the exit status for the pipeline.
• In this case exit status of zero means that
fred was found in who’s output.
The $? Variable
• The shell variable is
automatically set by the shell
to the exit status of the last
command executed.
$ cp phonebook phone2
$ echo $?
0
$ cp nosuch backup
cp: cannot access nosuch
$ echo $?
2
$ echo $?
0
$ who
root console Jul
wilma tty02 Jul
betty tty11 Jul
$ Who|grep wilma
wilma tty02 Jul
$ echo $?
0
$ Who|grep fred
$ echo $?
1
8 10:06
8 1:11
8 1:10
8 1:11
if command
$ cat on
#
# determine if someone is
# logged on
#
user ="$1"
if who | grep "$user"
then
echo "$user is logged on"
fi
$
$ who
root console
wilma tty02
tony tty03
betty tty11
joanne tty12
Jul 8 10:06
Jul 8 1:11
Jul 8 1:12
Jul 8 1:10
Jul 8 1:10
$ on tony
tony tty03 Jul 8 1:12
tony is logged on
$ on ann
joanne tty12 Jul 8 1:10
ann is logged on
First problem in on program
• We found couple of problems, the first
problem is, it displays the grep output.
• We can dispose of grep output by
redirecting it to system “garbage can”
/dev/null.
who | grep "$user" > /dev/null
Second problem in on program
• The second problem with on appears when he
program is executed with the argument ann.
• Even though ann is not logged on, grep
matched the character ann for the user joanne.
• To solve this problem match the pattern to the
beginning of the line by preceding character "^"
who | grep "^$user" > /dev/null
Example
$ cat on
#
# determine if someone is
# logged on
#
user ="$1"
if who | grep "^$user" >/dev/null
then
echo "$user is logged on"
fi
$
$ on ann
$
The test Command
• A test command used to test one or more
conditions in an if command.
test expression
• test evaluate expression, if result is true, it
return exit status of zero, otherwise nonzero.
name=julio
if test "$name" = julio
then
echo "Would you like to play a game? "
fi
The test Command
• Even if name is null, the shell will still pass three
arguments to test, the first one null
#Set the name to null
$ name=
$ test "$name" = julio
$ echo $?
1
$
The test string operators
• Returns TRUE (exit status of 0) if
string1=string2, string1 is identical to string2
String1 != string2, string1 is not identical to string2
String, string is not null
-n string, string is not null (a string must be seen by test)
-z string, string is null (a string must be seen by test)
Example test
$
$
$
0
$
$
$
$
1
$
day="monday"
test "$day" = monday
echo $?
True
day="monday "
test "$day" = monday
echo $?
False
$ day="monday "
$ test $day = monday
$ echo $?
0
$ blank="
"
$ test $blank
$ echo $?
True
it’s null
1
$ test "$blank"
$ echo $?
False
0
True
it’s not Null
Example test -z
test –z "$dataflag"
will return and exit status of 0 if dataflag doesn’t contain
any characters.
$ nullvar=
$ nonnullvar=abc
$ test –z "nullvar"
$ echo $?
0
$ test –z "nonnullvar"
$ echo $?
1
Example test -n
• Does nullvar have nonzero length? NO
$
$
$
$
1
nullvar=
nonnullvar=abc
test –n "nullvar"
echo $?
• Does nonnullvar have nonzero length? YES
$ test –n "nonnullvar"
$ echo $?
0
An Alternate Format of test
test expression
• This can also be
expressed in an alternate
format as
[ expression ]
$ [ –z "nonnullvar" ]
$ echo $?
1
if [ "$name" = julio ]
then
echo "How are you?"
fi
Integer Operators
•
•
•
•
•
•
int1
int1
int1
int1
int1
int1
–eq
–ge
–gt
–le
–lt
–ne
int2, int1 is equal to int2
int2, int1 is greater than or equal to int2
int2, int1 is greater than int2
int2, int1 is less than or equal to int2
int2, int1 is less than int2
int2, int1 is not equal to int2
Integer
• To see if $count variable has value equal to 0
(zero)
[ "$count" –eq 0 ]
[ "$choice" –lt 5 ]
[ "$index" –ne "$max" ] tests to see if the
value of index is not equal to the value of max.
[ "$#" –ne 0 ] tests to see if the number of
arguments passed to the command is not equal
to 0.
Integer Example
$
$

$
$
1

$
$
0

$
$
1
X1="005"
X2=" 10"
String comparison
[ "x1" = 5 ]
echo $?
'False
Integer comparison
[ "x1" -eq 5 ]
echo $?
'True
String comparison
[ "x2" = 10 ]
echo $?
'False

$
$
0
•
Integer comparison
[ "x2" -eq 10 ]
echo $?
'True
In first test, the string
comparison operator = is used.
• In second test, the Integer
comparison operator -eq is
used.
• The third and fourth tests are
similar, only in this case you
can see how even a leading
space stored in variable x2 can
influence a test made with a
string operator versus integer
operator.
File Operators
– d file, file is a directory
– f file, file is an ordinary file
– r file, file is readable by the process
– s file, file has nonzero length
– w file, file is writeable by the process
– x file, file is executable
File Operator Example
•
[
•
[
•
[
To see if file exist, and is an ordinary file
-f /usr/steve/phonebook ]
To see if file exist, and also readable file
-r /usr/steve/phonebook ]
To see if file contains at least one byte
-s /usr/steve/phonebook ]
if [ -s $ERRFILE ]
then
echo "Error found:"
cat $ERRFILE
fi
The Logical Negation Operator !
• The urinary logical negation operator ! Can be placed in
front of any other test expression to negate the result.
[ ! –r /usr/steve/phonebook ]
• Will return zero exit status (true), if phonebook is not
readable.
[ ! –f "$mailfile" ]
• Will return zero exit status (true), if file specified by
$mailfile does not exist.
[ ! "$x1" = "$x2" ]
• Will return zero exit status (true), if $x1 is not identical to
$x2.
[ ! "$x1" = "$x2" ] same as [ "$x1" != "$x2" ]
The Logical AND Operator -a
• The operator –a performs a logical AND
of two expressions and will return true only
if both are true.
[ -f "$mailfile" –a –r "$mailfile" ]
• Will return zero, if specified file is an
ordinary file and is readable by you.
The Logical AND Operator -a
• The command
[ "$count" –ge 0 –a "$count" –lt 10]
• Will return zero, if variable count contains
an integer value that is greater than or
equal to 0 but less than zero.
The Logical OR Operator -o
• The command
[ -n "$mailopt" –o –r $HOME/mailfile ]
• This command will be true if the variable
mailopt is not null or if the file
$HOME/mailfile is readable by you.
• The –o operator has lower precedence than the
–a operator
"$a" –eq 0 –o "$b" –eq 2 –a "$c" –eq 10
will be evaluated by test as
"$a" –eq 0 –o ("$b" –eq 2 –a "$c" –eq 10)
The else Construct
• A construct known as the else can be added to if command.
$ cat on
#
# determine if someone is logged on – version 3
#
User= "$1"
if who | grep "^$user" > /dev/null
then
echo "$user is logged on"
else
echo "$user is not logged on"
fi
The else Construct Example
$ who
root tty02 Jul 7 08:37
fred tty03 Jul 8 08:30
tony tty04 Jul 8 08:17
lulu tty05 Jul 8 08:27
taziz tty06 Jul 8 08:57
ahmed tty07 Jul 8 08:47
$ on pat
pat is not logged on
$ on tony
tony is logged on
The else Construct
$ cat on
#
# determine if someone is logged on – version 4
#
if [ "$#" –ne 1 ]
then
echo "Incorrect number of arguments"
echo "Usage: on user"
else
user= "$1"
if who | grep "^$user" > /dev/null
echo "$user is logged on"
else
echo "$user is not logged on"
fi
fi
The else Construct
$ on
Incorrect number of arguments
Usage: on user
$ on priscilla
priscilla is not logged on
$ on jo anne
Incorrect number of arguments
Usage: on user
The exit Command
• The built-in shell command called exit
enables you to immediately terminate
execution of your shell program.
exit n
• Where n is the exit status that you want to
returned.
The exit Command Example
$ cat rem
#
# remove someone to the phone book
#
if [ "$#" –ne 1 ]
then
echo "Incorrect number of arguments“
echo "Usage: rem name“
exit 1
fi
grep –v "$1" phonebook >/tmp/phonebook
mv /tmp/phonebook phonebook
$ rem Susan Goldberg
Incorrect number of arguments
Usage: rem name
The exit command will return 1 to signal failure
The elif command
• This sequence is used when you have multiple decision to make.
$ cat greetings
#
# Program to print a greeting
hour=`date|cut –c12-13`
If [ "$hour" –ge 0 –a "$hour" –le 11 ]
then
echo "Good morning"
elif [ "$hour" –ge 12 –a "$hour" –le 17 ]
then
echo "Good afternoon"
else
echo "Good evening"
fi
The case command
$ cat number
# Translate a digit to
English
#
if [ "$#" –ne 1 ]
then
echo "Usage: number digit"
exit 1
fi
case $1
in
0) echo
1) echo
2) echo
3) echo
4) echo
*) echo
esac
zero;;
one;;
two;;
three;;
four;;
Bad argument;;
$ number 0
zero
$ number 3
three
$ number
Usage: number digit
$ number 5
Bad argument
The case command
$ cat ctype
# classify char as argument
#
if [ "$#" –ne 1 ]
then
echo "Usage: ctype char"
exit 1
fi
char="$1"
numchar=`echo “$char”|wc –c`
if [ "$numchars" –ne 1 ]
then
echo Single Character Pl.
exit 1
fi
case "$char"
in
[0-9] ) echo digit;;
[a-z] ) echo lowercase;;
[A-Z] ) echo uppercase;;
*) echo Special Char;;
esac
$
$ ctype a
lowercase
$ ctype 7
Digit
$ ctype abc
Single Character Pl.
| Symbol
$ cat greetings
#
# Program to print a greeting – case version
#
hour=`date %H`
case "$hour"
in
0? | 1[01] ) echo "Good morning"
1[2-7]
) echo "Good afternoon"
*
) echo "Good evening"
esac
$ date
Fri Jul 19 15:07:48 EDT 1985
$ greetings
Good afternoon
The Null Command :
• The shell built-in null command.
:
• It is used to satisfy the requirement that a command
appear particularly in if command.
if grep "^$system " /usr/steve/systems>/dev/null
then
:
else
echo "$system is not a valid file system"
exit 1
fi
The && and || construct
• The shell has two special constructs && and || that
enable you to execute a command based upon whether
the preceding command succeeds or fails.
• If you write
command1 && command2
• command1 will be executed and it returns an exit status
of zero, then command2 will be executed. If command2
brought a nonzero exit status, then command2 get
skipped.
&& Example
• Sort bigdata > /tmp/sort1 && mv /tmp/sort1 bigdata
• The mv command will be executed only if the sort is
successful.
• Note that it is equivalent to writing
if sort bigdata > /tmp/sort1
then
mv /tmp/dort1 bigdata
fi
The || constructs
• The || construct works similarly, only the second command gets
executed only if the exit status of the first is non zero.
• So if you write
grep "$name" phonebook || echo "couldn’t find $name"
• then the echo command will get executed if grep fails
if grep "$name" phonebook
then
:
else
echo "Couldn’t find $name"
fi
The || constructs
• You can write a pipeline on either the left
or right-hand sides of these construct. On
the left, then exit status is tested is that of
the last command in the pipeline; thus
who| grep "$n" >/dev/null|| echo "$n not logged on"