You are not logged in.

#1 2010-10-01 01:09:58

Rad3k
Member
From: Poland
Registered: 2009-05-09
Posts: 36

[SOLVED] Weird way of testing for null string in sh.

It may be a dumb question, but I couldn't find the answer. Are there any reasons to use

if [ "x${string}" != "x" ]

instead of

if [ -n "${string}" ]

or just

if [ "${string}" ]

?
As for the first syntax, I can see some disadvantages (it's longer, less readable, probably also less efficient) while no obvious advantages over the other ones. Is the first version more portable, or something like that?

I ask because I'm writing my own encryption hook for mkinitcpio (to add support for resuming from encrypted swap), and I've encountered this syntax in existing code. Now I wonder whether it's safe to always go the usual way in this hook... hmm


Solved, see hbekel's answer

Last edited by Rad3k (2010-10-01 13:53:19)

Offline

#2 2010-10-01 02:28:31

falconindy
Developer
From: New York, USA
Registered: 2009-10-22
Posts: 4,111
Website

Re: [SOLVED] Weird way of testing for null string in sh.

Busybox supports the -z flag to check for nulls (the opposite of -n).

Offline

#3 2010-10-01 06:03:48

hbekel
Member
Registered: 2008-10-04
Posts: 311

Re: [SOLVED] Weird way of testing for null string in sh.

"The x"$foo" hack is required for code that must run on ancient shells which lack [[, and have a more primitive [, which gets confused if $foo begins with a -."

from http://mywiki.wooledge.org/BashPitfalls … bar.22_.5D

Offline

#4 2010-10-01 13:50:55

Rad3k
Member
From: Poland
Registered: 2009-05-09
Posts: 36

Re: [SOLVED] Weird way of testing for null string in sh.

Thanks hbekel smile
So portability (probably taken to the extreme) is the reason here. I wonder whether busybox's ash qualifies as such an ancient shell. Will have to check it. Marking as solved.

Offline

#5 2010-10-01 13:55:27

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: [SOLVED] Weird way of testing for null string in sh.

It's easier to port a shell than a shell script. -- Larry Wall
tongue

Offline

#6 2010-10-01 21:51:48

falconindy
Developer
From: New York, USA
Registered: 2009-10-22
Posts: 4,111
Website

Re: [SOLVED] Weird way of testing for null string in sh.

Busybox is far from an ancient shell. Its designed to be compact but still featureful. There's no need to use archaic portability tricks when -z is supported. Just quote the far for safety and move on.

Offline

Board footer

Powered by FluxBB