Binary operator is one that gets two operands. And this can be a pain in Bash.
Something I usually do a lot is to check if one number is larger than or equal to another. For this, I use the test
with the operator gt
:
if [ "$numero" -gt 2 ]; then
...
fi
Where can the main bottlenecks with binary operators arise in Bash? Well, in addition to the syntax with behavior well out of the pattern (from those who come from a more behaved world like C, Java or Pascal), we have such of the variable expansions.
What are these expansions? Well, you noticed I put quotes around $numero
? I did it with a single goal: if it has no value in $numero
, place the empty string.
Imagine a scenario where $numero
has no value; when doing variable expansion, my code would look like this:
if [ "" -gt 2 ]; then
...
fi
Now imagine that I had forgotten the quotation marks. My code would be expanded to the following:
if [ -gt 2 ]; then
...
fi
Note that in this second case, there is no operator on the left side of -gt
, which leads to an error of comparison!
The other point I spoke about was the non-standard syntax. If you are not careful, a short-circuit of commands may end up turning into the call of a routine in parallel or opening a pipeline.
For example, the short circuit operator AND &&
indicates that I only execute the command on the right if the command on the left returns true
(in the shell world, output code 0). The short circuit operator OR ||
indicates that I only execute the command on the right if the command on the left returns false
(in the shell world, output code other than 0).
So let’s go to the parallel processing operators and pipeline. The operator &
indicates that the command that proceeds must be executed in parallel; note that a simple typing error can transform the AND &&
the operator. The operator |
will create a pipeline between the command on the left and the command on the right; note that it is easy to type the OR ||
and fall into the pipe.
Note that in your code, the command test
is running in another thread as it is followed by &
.
For more readings, see Shell Script Swiss Army Knife by Aurelio Verde
I disagree with the explanation on if your script gives problem with "[" you will have to use it so double brackets "[[". Double brackets are aimed at more literal interpretation of what is written, without having to attach the idiosyncrasies of
bash
– Jefferson Quesado