Saturday 7 July 2012

Shell script - 2

Shell script - 2
To go to Shell script Session click here
To go to UNIX basic commands click here

Its time to learn operators


 Arithmetic Operator:
           
Symbol
Meaning
+
Addition
-
Minus(subtract)
*
Multiply
/
Divide
%
Modulus
=
Assignment
==
Equal to
!=
Not equal to

In the above the three given in red will be used with comparison and others will be used with expr.

Relation Operators/Comparative operators for numbers/integers:

Operator
Meaning
Usage Example
-eq
Equality condition
[$a –eq $b]
-ne
Not equal condition
[$a –ne $b]
-gt
Greater than condition
[$a –gt $b]
-lt
Less than Condition
[$a –lt $b]
-ge
Greater than equal to condition
[$a –ge $b]
-le
Lesser than equal to condition
[$a –le $b]

Boolean Operators:
Symbol/operator
Meaning
Usage Example
!
Not/Negation
[! [$a –eq $b]] if[$a –eq $b] evaluates to true ! ll make it false and vice versa
-o
OR
[ [$a –eq $b ] –o [-a –eq $c] that is any one condition need to be true
-a
AND
[ [$a –eq $b ] –a [-a –eq $c] that is both condition should be true


Operators used with Strings
Symbol/Operator
Meaning
Usage Example
=
Checks if both strings are equal
[ $str1 = $str2 ]
!=
Checks if both strings are not equal
[ $str1 != $str2 ]
-z
Checks for length is zero
[ $str1 –z $str2 ]
-n
Checks for length is not zero
[ $str1 –n $str2 ]

Files Operators

Symbol/Operator
Meaning
Usage Example
-b file
Checks if the file is block special file
[ -b $filename ]
-c file
Checks if the files is char special file
[ -c $filename ]
-d file
Checks if the file is directory
[ -d $filename ]
-e file
Check for file existence
[ -e $filename ]
-f file
Check if the file is ordinary file
[ -f $filename ]
-g file
Check if the file group id is set
[ -g $filename ]
-p file
Check if the file is a named pipe
[ -p $filename ]
-t file
Check if the file descriptor is open
[ -t $filename ]
-u file
Checks if the files set user id is set
[ -u $filename ]
-r file
Checks if the file is readable
[ -r $filename ]
-s file
Checks if the file size is greater than 0
[ -s $filename ]
-w file
Checks if the file is writable
[ -w $filename ]
-x file
Checks if the file is Executable
[ -x $filename ]

Example 6:
#!/bin/sh
filename=$1
if [-r filename] then
echo "file is readable"
elif [-x filename] then
echo "file is executable"
elif [-w filename] then
echo "file is writable"
else
echo "ERRROR: $filename HAS PERMISSION PROB"
fi


To go to next session click here don't forget to put your feed back as comments which encourages me to do this and you can also post your questions or solve/give answers for others questions, Thanks in advance friends.....




No comments:

Post a Comment