[colug-432] Shell Tests

jep200404 at columbus.rr.com jep200404 at columbus.rr.com
Tue Oct 6 17:21:56 EDT 2015


Which shell test would you choose? Why?
Would you choose a test not shown below? Why?

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. 

These tests worked the same:

    [ "${1:+is_set}" != "is_set" ]
    [ "z${1}" = "z" ]
    [ "${1}" = "" ]

The last of those above is curious.
Since it works the same as with 'z', why bother with the 'z'?

Only [ "${#}" -lt 1 ] was different, 
and seems more strictly correct 
unless an empty first argument is to be treated the 
same as no first argument.

    [user at colug ~]$ cat boo.sh 
    #!/bin/sh
    
    a="${1:+is_set}"
    echo "a is >$a<"
    
    if [ "${1:+is_set}" != "is_set" ]; then
        echo one
    fi
    
    b="z${1}"
    echo "b is >$b<"
    
    if [ "z${1}" = "z" ]; then
        echo two
    fi
    
    c="${1}"
    echo "c is >$c<"
    
    if [ "${1}" = "" ]; then
        echo tree
    fi
    
    d="${#}"
    echo "d is >$d<"
    
    if [ "${#}" -lt 1 ]; then
        echo for
    fi
    [user at colug ~]$ ./boo.sh 
    a is ><
    one
    b is >z<
    two
    c is ><
    tree
    d is >0<
    for
    [user at colug ~]$ ./boo.sh ''
    a is ><
    one
    b is >z<
    two
    c is ><
    tree
    d is >1<
    [user at colug ~]$ ./boo.sh ' '
    a is >is_set<
    b is >z <
    c is > <
    d is >1<
    [user at colug ~]$ ./boo.sh '' world
    a is ><
    one
    b is >z<
    two
    c is ><
    tree
    d is >2<
    [user at colug ~]$ ./boo.sh ' ' world
    a is >is_set<
    b is >z <
    c is > <
    d is >2<
    [user at colug ~]$ ./boo.sh hello world
    a is >is_set<
    b is >zhello<
    c is >hello<
    d is >2<
    [user at colug ~]$ 


More information about the colug-432 mailing list