test "$foo" = "$bar" vs test x"$foo" = x"$bar"

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

test "$foo" = "$bar" vs test x"$foo" = x"$bar"

Jordi Gutiérrez Hermoso-2
re: bug #44367.

I need a little help with my shell scripting.

What's the reason to have

    test x"$foo" = x"$bar"

vs

    test "$foo" = "$bar"

?

It was my understanding is that the intent of the former is to handle
the case where $foo or $bar is empty, but I thought the quotes handled
that.

That is, I thought you needed to either do

   test x$foo = x$bar

or

   test "$foo" = "$bar"

but having both the leading x and the quotes is redundant.

- Jordi G. H.




Reply | Threaded
Open this post in threaded view
|

Re: test "$foo" = "$bar" vs test x"$foo" = x"$bar"

Jordi Gutiérrez Hermoso-2
On Wed, 2015-02-25 at 11:27 -0500, Jordi Gutiérrez Hermoso wrote:
> but having both the leading x and the quotes is redundant.

btw, we have a lot of comparisons both with and without leading x's in
our configure.ac. I would like to normalise all usages one way or the
other, depending what is correct and portable across shells.

- Jordi G. H.



Reply | Threaded
Open this post in threaded view
|

Re: test "$foo" = "$bar" vs test x"$foo" = x"$bar"

Mike Miller
In reply to this post by Jordi Gutiérrez Hermoso-2
On Wed, Feb 25, 2015 at 11:27:56 -0500, Jordi Gutiérrez Hermoso wrote:
> That is, I thought you needed to either do
>
>    test x$foo = x$bar
>
> or
>
>    test "$foo" = "$bar"
>
> but having both the leading x and the quotes is redundant.

I'm not entirely sure, but I had thought the reason for the x"$foo"
pattern was in case $foo was something like "-d". Adding a known
character in front ensures that the test command doesn't try to
interpret it as an option and possibly throw an error. And the quotes
are to ensure that it's treated as a single argument whether it is
empty or has spaces or whatever.

We have several variables that we only ever set to "yes" or "no", so
quotes or any other special handling are not needed for those.
Variables that come from the environment or from command-line options
definitely need quotes, and may also need an x-prefix. I don't have an
example that demonstrates whether the x-prefix is needed or not.

--
mike