1745906 Members
4306 Online
108723 Solutions
New Discussion юеВ

Re: If [ ] and [[ ]]

 
SOLVED
Go to solution
Ryan Clerk
Frequent Advisor

If [ ] and [[ ]]

Hi,

I noticed that sometimes
"if [ $A = $B ]" is used and other times
"if [[ $A = $B ]]" is used. Is there a difference or is it just a personal choice?

TIA,
Ryan
4 REPLIES 4
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: If [ ] and [[ ]]

In more modern shells (Posix, ksh, ...) that support the "[[ ... ]]" syntax for if the difference is that "[[ .. ]]" is an internal (to the shell) test whereas "[ .. ]" invokes the external test command. The double brackets are thus more efficient.
If it ain't broke, I can fix that.
Sundar_7
Honored Contributor

Re: If [ ] and [[ ]]


And you cannot use boolean expressions with [[. You will need to use [ to use boolean operators

# S=1
# [[ $S -eq 10 -o $S -gt 10 ]]
ksh: syntax error: `-o' unexpected
# [ $S -eq 10 -o $S -gt 10 ]
#
Learn What to do ,How to do and more importantly When to do ?
A. Clay Stephenson
Acclaimed Contributor

Re: If [ ] and [[ ]]

I should also add that in addition the syntax changes a bit as well --- especially the boolean operators.

e.g. (and)

if [ ${A} = ${B} -a ${A} = ${C} ]

is written

if [[ ${A} = ${B} && ${A} = ${C} ]].

Similarly, -o (or) becomes ||.


If it ain't broke, I can fix that.
MAUCCI_2
Frequent Advisor

Re: If [ ] and [[ ]]

Another noticeable difference is that you can do pattern matching under [[ ]]

> if [[ "toto" = toto* ]]; then echo equals; else echo "not equal"; fi

equals

> if [ "toto" = toto* ]; then echo equals; else echo "not equal"; fi

not equal



http://www.kornshell.com/doc/faq.html

Q10. What is the difference between [...] and [[...]]?
A10. The [[...]] is processed as part of the shell grammar
whereas [...] is processed like any other command.
Operators and operands are detected when the command is
read, not after expansions are performed. The shell does not
do word splitting or pathname generation inside [[...]].
This allows patterns to be specified for string matching
purposes.