Home > database >  What does it mean in bash [ "abc" < $bar ]?
What does it mean in bash [ "abc" < $bar ]?

Time:11-19

Currently, I am learning bash. I wonder what the [ "abc" < $bar ] command means. I know that [] compares or tests their values. But how does the < operator work between abc string and $bar variable Can you please describe it?

CodePudding user response:

[ "abc" < $bar ] looks like an error by the programmer. We can rewrite it to [ "abc" ] < $bar with exactly the same meaning.

< is a redirection operator to read the input from a file named $bar. [ command ignores standard input, so any input is ignored. If $bar variable is empty, it will write a bash: $bar: ambiguous redirect message.

Then [ "abc" ] checks if abc is a non-empty string. It is not an empty string, so [ "abc" ] returns with zero exit status meaning success.

If the author of the code meant to compare strings lexicographically, he should have written [[ "abc" < "$bar" ]]. The [ command does not support < operator (see POSIX standard, in fact POSIX mentions that it is not included.). In Bash, [ "abc" '<' "$bar" ] would work, because [ is a builtin aliased to test (see output of help [), and the builtin test command does implement the string comparison operators < and >. But /usr/bin/[ a '<' b ] command results in /usr/bin/[: ‘<’: binary operator expected. [ external command does not support <.

Additionally, $bar is not quoted, so the result of $bar undergoes word splitting and filename expansion, which looks like another error. Remember to check your script by shellcheck .

[ "abc" < $bar ]
        ^-- SC2073 (error): Escape \< to prevent it redirecting (or switch to [[ .. ]]).
          ^--^ SC2086 (info): Double quote to prevent globbing and word splitting.
  •  Tags:  
  • bash
  • Related