Remember that [
is an alias to the command test
. The question is what would happen if your string started with a dash?
In old versions of test
when using the standard Bourne shell, you'd get an error:
$ test -gt = "some_string"
invalid argument
The same thing would happen with an if
$ string="-gt"
$ if [ "$string" = "some_other_string" ]
> then
> echo "Match"
> else
> echo "No Match"
> fi
if: invalid argument
That's because the test
command would see the parameter with a dash and assume that it's a command argument, then either it's an invalid command argument, or the format of the command is incorrect. If you use [[
instead of [
, it's not an issue at all because [[
is a built in test for the if
.
This is no longer an issue. The [
and test
are internal commands to both the Kornshell and BASH, and these shells can handle this issue. Even the newer versions of test are no longer thrown:
$ test -gt = "some_string" # No error.
$ echo $?
1
However, older scripts, and those people who either learned from an older timer, or were back writing scripts when system with 32 Mb of memory running on a 16 Mhz 386 chip with Xenix was a state of the art system have gotten into the habit. I use to use x
:
if [ x$var = x$foo ]