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

时间:2019-04-23 15:06:19

标签: bash

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?

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:4)

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

答案 2 :(得分:2)

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.