Licão 10 operators

39
Lesson 10 Shell Operators Arithmetic Evaluation Conditional Statements

Transcript of Licão 10 operators

Page 1: Licão 10 operators

Lesson 10• Shell Operators

• Arithmetic Evaluation

• Conditional Statements

Page 2: Licão 10 operators

Shell operators

Important Bourne Shell operators

• Arithmetic Operators

• Relational Operators

• Boolean Operators

• String Operators

• File Test Operators

Page 3: Licão 10 operators

Arithmetic Operators

Bourne shell didn't originally have any mechanism to perform simple arithmetic It uses external programs - awk or program expr.

#!/bin/shval=`expr 2 + 2` echo "Total value : $val"

result:

Total value : 4

• There must be spaces between operators and expressions 2+2 is not correct. it should be written as 2 + 2.

• Complete expression should be enclosed between `` (inverted commas)

Page 4: Licão 10 operators

Arithmetic Operators

Ex. variable a holds 10 and variable b holds 20 then:

+ Addition - Adds values on either side of the operator `expr $a + $b` will give 30

- Subtraction - Subtracts right hand operand from left hand operand `expr $a - $b` will give -10

* Multiplication - Multiplies values on either side of the operator `expr $a * $b` will give 200

/ Division - Divides left hand operand by right hand operand `expr $b / $a` will give 2

% Modulus - Divides left hand operand by right hand operand and returns remainder`expr $b % $a` will give 0

= Assignment - Assign right operand in left operanda=$b would assign value of b into a

== Equality - Compares two numbers, if both are same then returns true.[ $a == $b ] would return false

!= Not Equality - Compares two numbers, if both are different then returns true.[ $a != $b ] would return true

All conditional expressions are put inside square braces with one spaces around them.[ $a == $b ] is correct; [$a==$b] is incorrect.

All the arithmetical calculations are done using long integers.

Page 5: Licão 10 operators

Arithmetic expressions

#!/bin/sha=10 b=20 val=`expr $a + $b` echo "a + b : $val" val=`expr $a - $b` echo "a - b : $val" val=`expr $a \* $b` echo "a * b : $val" val=`expr $b / $a` echo "b / a : $val" val=`expr $b % $a` echo "b % a : $val" if [ $a == $b ] thenecho "a is equal to b" fi if [ $a != $b ] thenecho "a is not equal to b" fi

Exemple

Page 6: Licão 10 operators

Arithmetic expressions

a + b : 30 a - b : -10 a * b : 200 b / a : 2 b % a : 0 a is not equal to b

Exemple Result

• There must be spaces between operators and expressions 2+2 is not correct, as it should be written as 2 + 2.

• Complete expression should be enclosed between `` (inverted commas)

• use \ on the * symbol for multiplication.

• if...then...fi statement is a decision making statement (for later lessons:-)

Page 7: Licão 10 operators

Arithmetic expressions

$ let X=10+2*7$ echo $X24$ let Y=X+2*4$ echo $Y32

The let statement can be used to do mathematical functions

$ echo “$((123+20))”143$ VALORE=$[123+20]$ echo “$[123*$VALORE]”17589

arithmetic expression can be evaluated with $[expression] or $((expression))

Page 8: Licão 10 operators

Arithmetic expressions

$ vi arithmetic.sh#!/bin/bashecho -n “Enter the first number: ”; read xecho -n “Enter the second number: ”; read yadd=$(($x + $y)) sub=$(($x - $y)) mul=$(($x * $y)) div=$(($x / $y)) mod=$(($x % $y))Echo ”sum: $add”…

Exemple

echo “Sum: $add”echo “Difference: $sub”echo “Product: $mul”echo “Quotient: $div”echo “Remainder: $mod”

Exemple Result

Page 9: Licão 10 operators

Conditional StatementsConditionals let us decide whether to perform an action or not this decision is taken by evaluating an expression.

basic form:

if [ expression ];

then

statements

elif [ expression ];

then

statements

else

statements

fi

the elif (else if) and else sections are optional

Put spaces after [ and before ], and around the operators and operands.

Page 10: Licão 10 operators

ExpressionsAn expression can be:

• String comparison

• Numeric comparison

• File operators

• Logical operators

An expression is represented by $[expression] or $((expression))

Page 11: Licão 10 operators

Relational OperatorsNumber Comparisons Expression

Bourne Shell supports relational operators which are specific to numeric valuesThese operators do not work for string values unless their value is numeric. For example, following operators would work to check a relation between 10 and 20 as well as in between "10" and "20" but not in between "ten" and "twenty".

eq Check if value of two operands are equal or not, if yes then condition becomes true. [ $a -eq $b ] is not true.

-ne If value of two operands are equal or not, if values are not equal then condition becomes true. [ $a -ne $b ] is true.

-gt If the value of left operand is greater than the value of right operand, if yes then condition becomes true. [ $a -gt $b ] is not true.

-lt If the value of left operand is less than the value of right operand, if yes then condition becomes true. [ $a -lt $b ] is true.

-ge If the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. [ $a -ge $b ] is not true.

-le If the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. [ $a -le $b ] is true.

Ex. variable a holds 10 and variable b holds 20 then:

All conditional expressions would be put inside square braces with one spaces around them

[ $a <= $b ] is correct , [$a <= $b] is incorrect.

Page 12: Licão 10 operators

Relational OperatorsNumber Comparisons Expression

Simple Table

-eq compare if two numbers are equal-ge compare if one number is greater than or equal to a number-le compare if one number is less than or equal to a number-ne compare if two numbers are not equal-gt compare if one number is greater than another number-lt compare if one number is less than another number

[ n1 -eq n2 ] (true if n1 same as n2, else false)

[ n1 -ge n2 ] (true if n1greater then or equal to n2, else false)

[ n1 -le n2 ] (true if n1 less then or equal to n2, else false)

[ n1 -ne n2 ] (true if n1 is not same as n2, else false)

[ n1 -gt n2 ] (true if n1 greater then n2, else false)

[ n1 -lt n2 ] (true if n1 less then n2, else false)

Page 13: Licão 10 operators

Relational OperatorsNumber Comparisons Expression

#!/bin/sha=10b=20

if [ $a -eq $b ] then

echo "$a -eq $b : a is equal to b" else

echo "$a -eq $b: a is not equal to b" fiif [ $a -ne $b ] then

echo "$a -ne $b: a is not equal to b" else

echo "$a -ne $b : a is equal to b" fiif [ $a -gt $b ] then

echo "$a -gt $b: a is greater than b" else

echo "$a -gt $b: a is not greater than b" fi

if [ $a -lt $b ] then

echo "$a -lt $b: a is less than b"else

echo "$a -lt $b: a is not less than b"fi if [ $a -ge $b ] then

echo "$a -ge $b: a is greater or equal to b" else

echo "$a -ge $b: a is not greater or equal to b" fi if [ $a -le $b ] then

echo "$a -le $b: a is less or equal to b" else

echo "$a -le $b: a is not less or equal to b" fi

Exemple

Page 14: Licão 10 operators

Relational OperatorsNumber Comparisons Expression

10 -eq 20: a is not equal to b 10 -ne 20: a is not equal to b 10 -gt 20: a is not greater than b 10 -lt 20: a is less than b 10 -ge 20: a is not greater or equal to b 10 -le 20: a is less or equal to b

Exemple Result

Page 15: Licão 10 operators

Relational OperatorsNumber Comparisons Expression

Exemple

$ vi number.sh

#!/bin/bashecho -n “Enter a number 1 < x < 10: "read numif [ “$num” -lt 10 ]; then

if [ “$num” -gt 1 ]; then echo “$num*$num=$(($num*$num))”

else echo “Wrong insertion !”

fielse

echo “Wrong insertion again !”fi

Page 16: Licão 10 operators

String OperatorsString Comparisons Expressions

= Checks if value of two operands are equal or not, if yes then condition becomes true. [ $a = $b ] is not true.

!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. [ $a != $b ] is true.

-z Checks if the given string operand size is zero. If it is zero length then it returns true.[ -z $a ] is not true.

-n Checks if the given string operand size is non-zero. If it is non-zero length then it returns true. [ -z $a ] is not false.

Str Check if str is not the empty string. If it is empty then it returns false. [ $a ] is not false.

Ex. variable a holds “abc” and variable b holds “efg” then:

Page 17: Licão 10 operators

String OperatorsString Comparisons Expressions

Simple Table

= compare if two strings are equal!= compare if two strings are not equal-n evaluate if string length is greater than zero-z evaluate if string length is equal to zero

[ s1 = s2 ] (true if s1 same as s2, else false)[ s1 != s2 ] (true if s1 not same as s2, else false)[ s1 ] (true if s1 is not empty, else false)[ -n s1 ] (true if s1 has a length greater then 0, else false)[ -z s2 ] (true if s2 has a length of 0, otherwise false)

Page 18: Licão 10 operators

String OperatorsString Comparisons Expressions

#!/bin/sh

a="abc" b="efg"

if [ $a = $b ] thenecho "$a = $b : a is equal to b" elseecho "$a = $b: a is not equal to b" fi

if [ $a != $b ] thenecho "$a != $b : a is not equal to b" elseecho "$a != $b: a is equal to b" fi

Exemple

if [ -z $a ] thenecho "-z $a : string length is zero" elseecho "-z $a : string length is not zero" fi

if [ -n $a ] thenecho "-n $a : string length is not zero" elseecho "-n $a : string length is zero" fi

if [ $a ] thenecho "$a : string is not empty" elseecho "$a : string is empty" fi

Page 19: Licão 10 operators

String OperatorsString Comparisons Expressions

abc = efg: a is not equal to b abc != efg : a is not equal to b -z abc : string length is not zero -n abc : string length is not zero abc : string is not empty

Exemple Result

Page 20: Licão 10 operators

String OperatorsString Comparisons Expressions

$ vi user.sh

#!/bin/bashecho -n “Enter your login name: "read nameif [ “$name” = “$USER” ]; then

echo “Hello, $name. How are you today ?”else

echo “You are not $USER, so who are you ?”fi

Exemple

Page 21: Licão 10 operators

Boolean OperatorsLogical operators Expressions

! This is logical negation. This inverts a true condition into false and vice versa.

[ ! false ] is true.

-o This is logical OR. If one of the operands is true then condition would be true.

[ $a -lt 20 -o $b -gt 100 ] is true.

-a This is logical AND. If both the operands are true then condition would be true otherwise it would be false.

[ $a -lt 20 -a $b -gt 100 ] is false.

Ex. variable a holds 10 and variable b holds 20 then:

Page 22: Licão 10 operators

Boolean OperatorsLogical operators Expressions

Simple Table

! negate (NOT) a logical expression

-a logically AND two logical expressions

-o logically OR two logical expressions

#!/bin/bashecho -n “Enter a number 1 < x < 10:”read numif [ “$num” -gt 1 –a “$num” -lt 10 ]; then

echo “$num*$num=$(($num*$num))”else

echo “Wrong insertion !”fi

Exemple

Page 23: Licão 10 operators

Boolean OperatorsLogical operators Expressions

a=10 b=20 if [ $a != $b ] then

echo "$a != $b : a is not equal to b" else

echo "$a != $b: a is equal to b" fiif [ $a -lt 100 -a $b -gt 15 ] then

echo "$a -lt 100 -a $b -gt 15 : returns true" else

echo "$a -lt 100 -a $b -gt 15 : returns false" fi if [ $a -lt 100 -o $b -gt 100 ] then

echo "$a -lt 100 -o $b -gt 100 : returns true" else

echo "$a -lt 100 -o $b -gt 100 : returns false" fi if [ $a -lt 5 -o $b -gt 100 ] then

echo "$a -lt 100 -o $b -gt 100 : returns true" else

echo "$a -lt 100 -o $b -gt 100 : returns false" fi

Exemple

Page 24: Licão 10 operators

Boolean OperatorsLogical operators Expressions

10 != 20 : a is not equal to b 10 -lt 100 -a 20 -gt 15 : returns true 10 -lt 100 -o 20 -gt 100 : returns true 10 -lt 5 -o 20 -gt 100 : returns false

Exemple Result

Page 25: Licão 10 operators

File Test OperatorsBoolean Check condition

-b file Checks if file is a block special file if yes then condition becomes true. [ -b $file ] is false

-c file Checks if file is a character special file if yes then condition becomes true. [ -b $file ] is false

-d file Check if file is a directory if yes then condition becomes true. [ -d $file ] is not true

-f file Check if file is an ordinary file as opposed to a directory or special file if yes then condition becomes true

[ -f $file ] is true

-g file Checks if file has its set group ID (SGID) bit set if yes then condition becomes true. [ -g $file ] is false

-k file Checks if file has its sticky bit set if yes then condition becomes true. [ -k $file ] is false

-p file Checks if file is a named pipe if yes then condition becomes true. [ -p $file ] is false

-t file Checks if file descriptor is open and associated with a terminal if yes then condition becomes true

[ -t $file ] is false

-u file Checks if file has its set user id (SUID) bit set if yes then condition becomes true. [ -u $file ] is false

-r file Checks if file is readable if yes then condition becomes true. [ -r $file ] is true

-w file Check if file is writable if yes then condition becomes true. [ -w $file ] is true

-x file Check if file is execute if yes then condition becomes true. [ -x $file ] is true

-s file Check if file has size greater than 0 if yes then condition becomes true. [ -s $file ] is true

-e file Check if file exists. Is true even if file is a directory but exists. [ -e $file ] is true

Ex. file holds an existing file name "test" whose size is 100 bytes and has read, write and execute permission on

Page 26: Licão 10 operators

File Test OperatorsBoolean Check condition

Simple Table

-d check if path given is a directory-f check if path given is a file-e check if file name exists-r check if read permission is set for file or directory-s check if a file has a length greater than 0-w check if write permission is set for a file or directory-x check if execute permission is set for a file or directory

[ -d scripts ] (true if scripts is a directory, otherwise false)[ -f scripts ] (true if scripts is a file, otherwise false)[ -e scripts ] (true if scripts exists, otherwise false)[ -s scripts ] (true if scripts length is greater then 0, else false)[ -r scripts ] (true if scripts has the read permission, else false)[ -w scripts ] (true if scripts has the write permission, else false)[ -x scripts ] (true if scripts has the execute permission, else false)

Page 27: Licão 10 operators

File Test OperatorsBoolean Check condition

#!/bin/bashif [ -f /etc/fstab ];

thencp /etc/fstab .

echo “Done.”elseecho “This file does not exist.”

exit 1fi

Exemple

Page 28: Licão 10 operators

File Test OperatorsBoolean Check condition

Exercice

Write a shell script which:• accepts a file name• checks if file exists• if file exists, copy the file to the same name + .bak + the current date

(if the backup file already exists ask if you want to replace it)

When done you should have the original file and one with a .bak at the end.

Page 29: Licão 10 operators

File Test OperatorsBoolean Check condition

Exemple

Assume a variable file holds an existing file name "/root/scripts/user.sh" whose size is 100 bytes and has read, write and execute permission on:

#!/bin/shfile="/root/scripts/user.sh"

if [ -r $file ] thenecho "File has read access" elseecho "File does not have read access" fi if [ -w $file ] thenecho "File has write permission" elseecho "File does not have write permission" fi if [ -x $file ] thenecho "File has execute permission" elseecho "File does not have execute permission" fi

if [ -f $file ] thenecho "File is an ordinary file" elseecho "This is special file" fi if [ -d $file ] thenecho "File is a directory" elseecho "This is not a directory" fi if [ -s $file ] thenecho "File size is zero" elseecho "File size is not zero" fi if [ -e $file ] thenecho "File exists" elseecho "File does not exist" fi

Page 30: Licão 10 operators

File Test OperatorsBoolean Check condition

File has read accessFile has write permissionFile has execute permissionFile is an ordinary file This is not a directory File size is zero File exists

Exemple Result

Page 31: Licão 10 operators

C Shell OperatorsArithmetic and Logical Operators

( ) Change precedence

~ 1's complement

! Logical negation

* Multiply

/ Divide

% Modulo

+ Add

- Subtract

<< Left shift

>> Right shift

== String comparison for equality

!= String comparison for non equality

=~ Pattern matching

& Bitwise "and"

^ Bitwise "exclusive or"

| Bitwise "inclusive or"

&& Logical "and"

|| Logical "or"

++ Increment

-- Decrement

= Assignment

*= Multiply left side by right side and update left side

/= Divide left side by right side and update left side

+= Add left side to right side and update left side

-= Subtract left side from right side and update left side

^= "Exclusive or" left side to right side and update left side

%= Divide left by right side and update left side with remainder

Page 32: Licão 10 operators

C Shell OperatorsFile Test Operators

-r file Checks if file is readable if yes then condition becomes true.

-w file Check if file is writable if yes then condition becomes true.

-x file Check if file is execute if yes then condition becomes true.

-f file Check if file is an ordinary file as opposed to a directory or special file if yes then condition becomes true.

-z file Check if file has size greater than 0 if yes then condition becomes true.

-d file Check if file is a directory if yes then condition becomes true.

-e file Check if file exists. Is true even if file is a directory but exists.

-o file Check if user owns the file. It returns true if user is the owner of the file.

Page 33: Licão 10 operators

Korn Shell OperatorsArithmetic and Logical Operators

+ Unary plus

- Unary minus

!~ Logical negation; binary inversion (one's complement)

* Multiply

/ Divide

% Modulo

+ Add

- Subtract

<< Left shift

>> Right shift

== String comparison for equality

!= String comparison for non equality

=~ Pattern matching

& Bitwise "and"

^ Bitwise "exclusive or"

| Bitwise "inclusive or"

&& Logical "and"

|| Logical "or"

++ Increment

-- Decrement

= Assignment

Page 34: Licão 10 operators

Korn Shell OperatorsFile Test Operators

-r file Checks if file is readable if yes then condition becomes true.

-w file Check if file is writable if yes then condition becomes true.

-x file Check if file is execute if yes then condition becomes true.

-f file Check if file is an ordinary file as opposed to a directory or special file if yes then condition becomes true.

-s file Check if file has size greater than 0 if yes then condition becomes true.

-d file Check if file is a directory if yes then condition becomes true.

-e file Check if file exists. Is true even if file is a directory but exists.

Page 35: Licão 10 operators

Korn/C Shell Logical OperatorsExemple

#!/bin/bashecho -n "Enter a number 1 < x < 10: "read numif [ “$number” -gt 1 ] && [ “$number” -lt 10 ]; then

echo “$num*$num=$(($num*$num))”else

echo “Wrong insertion !”fi

Page 36: Licão 10 operators

Exemple

$ vi iftrue.sh#!/bin/bashecho “Enter a path: ”; read xif cd $x; then

echo “I am in $x and it contains”; lselse

echo “The directory $x does not exist”;exit 1

fi

$ iftrue.shEnter a path: /homeuserid otherid …

$ iftrue.shEnter a path: blahThe directory blah does not exist

Page 37: Licão 10 operators

Shell ParametersPositional parameters

Variable Description

$0 The filename of the current script.

$n These variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on).

$# The number of arguments supplied to a script.

$* All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1 $2.

$@ All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to $1 $2.

$? The exit status of the last command executed.

$$ The process number of the current shell. For shell scripts, this is the process ID under which they are executing.

$! The process number of the last background command.

Page 38: Licão 10 operators

Positional parameters are assigned from the shell’s argument when it is invoked.

Positional parameter “N” may be referenced as “${N}”,

or as “$N” when “N” consists of a single digit.

$# is the number of parameters passed

$0 returns the name of the shell script running as well as its location in the file system

$* gives a single word containing all the parameters passed to the script

$@ gives an array of words containing all the parameters passed to the script

$ cat sparameters.sh#!/bin/bashecho “$#; $0; $1; $2; $*; $@”

$ sparameters.sh arg1 arg22; ./sparameters.sh; arg1; arg2; arg1 arg2; arg1 arg2

Shell ParametersPositional parameters

Page 39: Licão 10 operators

Shell ParametersPositional parameters

$ vi trash.sh #!/bin/bashif [ $# -eq 1 ];then

if [ ! –d “$HOME/trash” ];then

mkdir “$HOME/trash”fimv $1 “$HOME/trash”

elseecho “Use: $0 filename”exit 1

fi