Reputation: 717
Why does this line of code print ?
if [ "a" < "a" ]; then echo wow; fi
Also this line:
if [ "a" > "a" ]; then echo woow; fi
Upvotes: 1
Views: 74
Reputation: 289825
You are not comparing strings. <
is a redirection operator so in fact you are checking the success of such operation. And it is valid because you happen to have a file a
in the directory you are running the command!
See what happens if the file a
is not present:
$ [ "a" < "a" ] && echo "yes"
bash: no such file or directory: a
Let's create it and check again:
$ touch a
$ [ "a" < "a" ] && echo "yes"
yes
If you want to do so, use [[
. From 3.2.4.2 Conditional Constructs:
[[…]]
When used with [[, the < and > operators sort lexicographically using the current locale.
$ [[ "a" < "a" ]] && echo "yes" || echo "no"
no
Upvotes: 4
Reputation: 2243
To stop bash from interpreting the <
and >
as pipes, you can escape them with a backslash, or surround it with quotes like you would with every other string.
if [ "a" \< "a" ]; then echo "wow"; fi;
if [ "a" "<" "a" ]; then echo "wow"; fi;
The [
aka test
command will interpret its parameters as strings like any other unix command. Note that this won't resolve to true, because they are equal and thus not lexically sortable. You would need to include the equality yourself.
if [ "a" \< "a" ] || [ "a" = "a" ]; then echo "wow"; fi;
The <
and >
operators are not part of the POSIX specification of test, so it is a shell-specific feature and may not work or behave differently with other shell implementations.
Upvotes: 3