Tuesday, 26 January 2016

Numeric , String and File Comparators

test:

When you use if to evaluate epressions, you need the test statement because the true or flase vlaues returned by expressions can't directly handled by if.
test works in three ways
1) Compares two numbers
2)Compares two strings or single one for null values
3)checks a file attributes.

Numeric Comparison:

Operator    Meaning
-eq             Equal
-gt              Greater than
-lt              Less than
-ne            Not equal
-ge           Greater than Equal
-le             Less Than equal


x= 5 ; y =7

test $x -eq $y ; echo $?
1                                       not equal

String Comparators:

s1 = s2     string s1 = s2
s1 ! = s2   string s1 ! = s2
-n stg        string is not null
-z stg        string is  null

File Comparators:

There are following operators to test various properties associated with a Unix file.

Assume a variable file holds an existing file name "test" whose size is 100 bytes and has read, write and execute permission on −

Show Examples

Operator Description Example
-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. [ -c $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.





1 comment: