Binary operator is one that receives two operands. And this can be a pain in Bash.
Something I usually do is check if one number is greater than or equal to another. For this, I use test
with the gt
operator:
if [ "$numero" -gt 2 ]; then
...
fi
Where can the main bottlenecks with Bash operators appear? Well, in addition to syntax with well-non-standard behaviors (from those who come from a more behaved world like C, Java, or Pascal), we have such variables expansions.
What are these expansions? Well, did you notice that I put quotation marks around $numero
? I did this with a single goal: if it does not have value in $numero
, put the string empty.
Imagine a scenario where $numero
has no value; when doing the variable expansion, my code would look like this:
if [ "" -gt 2 ]; then
...
fi
Now imagine that I had forgotten the quotes. 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 causes a comparison error!
The other point I mentioned was about nonstandard syntax. If you are not careful, a short-circuit of commands may end up being called a routine in parallel or opening a pipeline.
For example, the shortcuts operator &&
indicates that I only execute the command on the right if the command on the left returns true
(in the shell world, exit code 0) . The OR % shortcuts operator indicates that I only execute the command on the right if the command on the left returns ||
(in the shell world, exit code other than 0). >
So let's go to the parallel processing and pipeline operators. The false
operator indicates that the command that proceeds must be executed in parallel; realize that a simple typo might turn AND &
into this 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 miss typing OR |
and falling into the pipe.
Note that in your code, the ||
command is running on another thread because it is followed by test
.
For more readings, check out the Shell Kilt Swiss Knife by Aurélio Verde