Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I have the following questions.
1. What is the difference between [[..]] and [..]? Why does first statement below works and second does not?
[[ 2-lt 3 && 3 -lt 4 ]] && echo yes
[ 2-lt 3 && 3 -lt 4 ] && echo yes2. What is the difference between the 2 kinds of statement below? Why would someone prefer one over the other?
if [[ 3 -gt 2 ]]; then
echo yes
fiif [[ 3 -gt 2 ]]
then
echo yes
fi3. What is the difference between the 2 kinds of statement below? Why would someone prefer one over the other?
val=$(whoami)
(vs)
val=`whoami`

1) double brackets [[...]] evaluates the expression between them and sets the unix exit code - either to 0 for true of nonzero for false. This is why 1 works and 2 doesn't.
The single brackets [] are used in such statements as:
while [ $x -gt 0 ]
do
.
.
doneand ksh array declarations and use.
2) Essentially, there's no difference betweent the two if statements. The semicolon before the 'then' allows placing the then on the same line as the rest of the if. Pick one method and stick with it.
3) Below are two examples of command substitution:
val=$(whoami)
(vs)
val=`whoami`The first is ksh while the other is bourne shell, sh. The ksh method doesn't work with bourne, but the sh works on ksh.
The ksh purests claim the sh method is obsolete, and could disappear in the future (according to Rosenblatt's "Learning the Korn Shell).
Personally, if portability is an issue, use the sh method.
Regards,
Nails

Regarding question #1, the single brackets also represent an expression to be evaluated as true or false. You can use either of two forms (see man test):
if test 2 -lt 3 or you could use:
if [ 2 -lt 3 ]
and test will also handle multiple tests, but as you discovered, shell operators like && and || cannot be used here. Instead, use -a or -o for and and or :[ 2 -lt 3 -a 3 -lt 4 ] && echo yes

Speaking as a ksh purist myself, I always use the ksh [[ ... ]] and $() instead of the sh [ ... ] and `...`. I also never use -gt, since ksh has integer expressions such as (( x > y )).
One great advantage of $() is that it nests better, e.g:
grep -l three $(grep -l two $(grep -l one *))

Great input - my preferences also. I just wanted to show jigujigu the proper syntax for his posted question.

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |