[colug-432] Shell Tests

Stephen Potter spp at unixsa.net
Wed Oct 7 08:21:19 EDT 2015



On 10/6/2015 6:21 PM, Rob Stampfli wrote:
> On Tue, Oct 06, 2015 at 05:21:56PM -0400, jep200404 at columbus.rr.com wrote:
>> I saw a shell test like [ "z${1}" = "z" ],
>> which got me wondering, why bother with the 'z'?
>> Is there some subtle behavior, perhaps when there
>> is no "${1}" argument? So I experimented.
> It used to be that the "test" command got confused when the first
> argument started with a dash, so shell programmers routinely
> prepended an alpha to cover this case.

Not only just the dash, but sh (and ksh, I seem to remember) could not 
distinguish between a null and nothing, so even when there was a value 
to $1, the test '[ "$var" = "" ]' would return a syntax error because 
there was no second argument to the test.

When I go into work in a little while, I'll test this on AIX - the only 
"traditional" commercial Unix I currently have access to - and see if 
that is still the case.

As to the original question (assuming I'd even write in shell 
anymore....), it is one of those "it depends" answers.  If I have any 
thought that the script will be used across multiple OSes (not just 
Linux, but Solaris, AIX, HPUX), I would use the traditional "x$1", 
because it is more portable and more likely to work.  If I know it will 
only ever be used on Linux, then I would be fine with a bash specific style.

-spp


More information about the colug-432 mailing list