Bash comparison and expression operators
-
test
is a shell built-in which (obviously) tests for some given condition. Some older shells need a special command. So you'll find also a program at/usr/bin/test
. -
[
is also a program to test for some condition. This software needs also a closing bracket and you can find it at/usr/bin/[
. -
[[…]]
is an alternative totest
and[
. It was developed for the Korn shell (ksh
). But you also find it in Bash versions greater than 2 and in the Z Shell. The double brackets have some nifty features:- The shell does no word splitting or file name expansion.
- You need no quoting.
- Instead of
-a
(AND) or-o
(OR) you can use&&
or||
. - The
=
can do a lot more.
-
((…))
is equivalent tolet
. So basically((expression))
is the same aslet "expression"
. However withlet
you can use more than one expression, but double braces only allow one expression. -
$((…))
(and also$[…]
) does some calculation. You shell tries to calculate the expression inside the braces and replaces the expression with the result. Soecho $((1+1))
leads toecho 2
. So your shells prints the number 2.
Every time when you want to compare two numbers you should use the option with a dash and two letters (-ge
, -lt
etc.). If you want to compare strings you should use =
or !=
.
Your question regarding escaping is quite hard to answer. Because it depends on the software you use besides from the shell. So i.e. grep
and grep -E
need different escaping. This is also the case with sed
, awk
and others. So the best option is to have a look at the manpage. After some time you get accustomed and know when to use escaping.