tamewhale
tamewhale

Reputation: 1061

Why does escaping greater than or less than work in bash string comparisons?

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?

Upvotes: 4

Views: 2583

Answers (3)

Florian Schlag
Florian Schlag

Reputation: 669

If you escape a character in bash your basically telling bash to pass the escaped character "as it is" to the underlying command.

In your case (if-statement) the part in the brackets is passed to the "test" command: https://ss64.com/bash/test.html

If you don't escape, the "<" operator, it is first interpreted by bash and afterwards the result of this interpretation (a < b) is pased to the test command.

Upvotes: 2

ruakh
ruakh

Reputation: 183371

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).

Upvotes: 6

chepner
chepner

Reputation: 531325

[ 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.

Upvotes: 5

Related Questions