If I try something like
if [ a < b ]
in bash it interprets it as trying to pipe one file to another. If I want to do a string comparison I know I should escape the operator like this:
if [ a \< b ]
I know I could use [[ to get around this but my question is, why does escaping like this work?
In essence, [
is a program that does what you want when its arguments are a
, <
, b
, and ]
. (In fact, Bash implements [
as a builtin, but it implements it as if it were a separate program, rather than treating it specially. This is for compatibility with systems where [
is literally a separate program on the path.)
So, just as writing echo a \< b
or echo a '<' b
or echo a "<" b
lets you call echo
with the arguments a
, <
, and b
(so as to print a < b
), writing [ a \< b ]
or [ a '<' b ]
or [ a "<" b ]
lets you call [
with the arguments a
, <
, b
, and ]
(so as to test whether a
is less than b
).
[
is an ordinary command, so if you don't escape it, it is parsed as a command with 2 arguments, a
and ]
. The < b
is processed as an input redirection and removed from the command line before [
is executed. That is, [ a < b ]
and [ a ] < b
are equivalent.
<
is not a standard operator supported by [
; bash
's implementation allows for such comparisons, but if you are relying on one non-standard extension, you may as well rely on [[
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With