zhufeng
zhufeng

Reputation: 35

Wrong output of " if [ -z $var ] " in aix ksh

I used a " if [ -z $var ] " in a script, but when I run it in aix ksh, the result is completely wrong and seems to have sytax error.

aixtest:/tmp# ls -a 
.   ..  a.sh    b.sh
aixtest:/tmp# ls -a | grep -i abc
aixtest:/tmp# all=`ls -a | grep -i abc`
aixtest:/tmp# echo $all

aixtest:/tmp# if [ -z $all ]; then echo "empty"; else echo "not empty"; fi;
ksh: test: 0403-004 Specify a parameter with this command.
not empty
aixtest:/tmp# if [ ! -z $all ]; then echo "not empty"; else echo "empty"; fi;
empty
aixtest:/tmp# oslevel -s 
6100-08-03-1339
aixtest:/tmp# echo $SHELL
/usr/bin/ksh

The script above, $all should be empty, but the output is wrong and I got a error saying that "ksh: test: 0403-004 Specify a parameter with this command."

After that I run this script in a HMC shell, which is a Linux distribution, output is correct.

hscpe@IDCP780HMC1:~> ls -a
.   ..  a.sh    b.sh
hscpe@IDCP780HMC1:~> ls -a | grep -i abc
hscpe@IDCP780HMC1:~> all=`ls -a | grep -i abc`
hscpe@IDCP780HMC1:~> echo $all

hscpe@IDCP780HMC1:~> if [ -z $all ]; then echo "empty"; else echo "not empty"; fi;
empty
hscpe@IDCP780HMC1:~> if [ ! -z $all ]; then echo "not empty"; else echo "empty"; fi;
empty
hscpe@IDCP780HMC1:~> uname -a 
Linux IDCP780HMC1 2.6.32-358.23.2.79.hmc7_4p.x86_64 #1 SMP Wed Nov 12 12:50:34 CST 2014 x86_64 x86_64 x86_64 GNU/Linux
hscpe@IDCP780HMC1:~> echo $SHELL
/bin/hmcbash

So where is the problem? Did I misuse "if" syntax in aix ksh or it is a bug ?

Upvotes: 1

Views: 765

Answers (2)

R Hyde
R Hyde

Reputation: 10409

It doesn't work because the shell interprets it as if [ -z ]. To make it work, you need to quote it.

This example is from AIX 7.1.

$ echo $SHELL
/usr/bin/ksh
$ all=""

Not quoted:

$ if [ -z $all ]; then echo "empty"; else echo "not empty"; fi;
ksh: test: argument expected
not empty

Quoted:

$ if [ -z "$all" ]; then echo "empty"; else echo "not empty"; fi;
empty

Upvotes: 0

Ewan Mellor
Ewan Mellor

Reputation: 6847

In some shells you'd have to quote the variable. I presume that's what's happening here (though I've never used AIX ksh).

if [ -z "$all" ]; ...

Upvotes: 1

Related Questions