Tuesday, May 17, 2011

Comparators in shell

In case of shell comparison one need to be very careful as one extra space may lead to the code throwing errors

For example :
if [$dd=1]

This is completely wrong as it will throw a "syntax error near unexpected token near then"
as there are three errors in this:
1)there must be minimum of one space between if and square bracket "["
2)For comparison in shell  ,there must be minimum of one space before and after the equal to sign"="
3)minimum of one space needed between 1 and closing bracket
giving more spaces will not cause error to happen.

proper code:

if  [ $dd = 1 ]

Shell assignments:

Ironic in the case of assignments when compared to comparison,is that there should not be any space before and after the equal-to sign("=")

Inside the shell file you provide like this:
gg  =  1

This will throw a critical error like "unary operater expected " and "command not found"
So it is must in Shell that the assignments must not have space before and after the "=" sign.
It should be:

Checking not-equal condition in Shell:

you can use "-ne" or "!= "  can be used for numbers.

you can use "!=" for comparing strings are not equal.

Logical Operators in Shell:

and     -a  can be used

cond1 -a  cond2  -  True if both conditions are true.

ex: [  $gg -eq  1 -a $cc -eq  2 ]  .Maintain spaces here else you may get "  Too many arguments error"

or     -  o can be used

ex: [ $gg -eq 1 -o $cc -eq   2 ]

Checking files in Shell:

-f somefile True if somefile exists and is an ordinary file.
-d somefile True if somefile exists and is a directory.
-s somefile True if somefile contains data (the size is not zero).
-r somefile True if somefile is readable.
-w somefile True if somefile is writable.
-x somefile True if somefile is executable.

No comments:

Post a Comment