Saturday, July 18, 2009

Difference between single square and double square brackets in conditional check in shell scripting

1. [ conditional check ] -> Variables used in the conditional check should have value, otherwise exception will be thrown during the execution.

2. [[ cond check ]] -> Exception will not thrown, even if variable don't have value or not received any value during the execution.

So, it is advisable to use single square bracket always to ensure whether we are receiving the value and doing the conditional checking.

example:
echo "Enter your name: "
read NAME
if [[ $NAME == "sujay" ]]
then
echo Your name is $NAME
else
echo Your name is $NAME from else part
fi

$ ksh doublesquare.sh
Enter your name:
sujay
Your name is sujay


$ ksh doublesquare.sh
Enter your name:

Your name is from else part


Note: If double square bracket is replaced with single: if [ $NAME == "sujay" ]
$ ksh singlesquare.sh
Enter your name:
sujay
Your name is sujay

$ ksh singlesquare.sh
Enter your name:

singlesquare.sh[4]: test: 0403-004 Specify a parameter with this command.
Your name is from else part

No comments: