I came across this construct to test whether the shell variable $foo
, which could contain any arbitrary string, matched foo
:
[ "x$foo" = "xfoo" ]
The purpose of prefixing with x
was never explained. This looks like an attempt to avoid errors that might arise when $foo
contains strings special to test like =
, -f
, (
, or !
. The GNU info manual indicates compound expressions involving -a
and -o
can lead to ambiguity, so I am primarily interested in simple (i.e., not compound) statements. I had a hard time searching for more information on this. I have not been able to devise an example of an arbitrary string that caused GNU test
to fail in an unexpected manner, although I freely admit I'm not that clever.
My questions:
- What reasons are there to prefix parameter substitutions in
test
? - Is there an example of a simple (i.e., not compound) statement involving naive parameter substitution (i.e., no prefix protection) that causes
test
to give unusual results?
I mostly use GNU tools on linux, but for the sake of portability, I am interested in whether test
on other platforms as well.
test
. I think that on very very old implementations, null-string arguments may be handled badly/differently, but I don't have a copy of the original Bourne shell to check. I seem to recall reading about this on this site before, though. You have my +1 for a good question. – Wildcard Sep 19 '17 at 23:41test
is specially ambiguos when the actualtest
called is/bin/test
. Please read this and this. – Sep 20 '17 at 01:47