Sunday, November 24, 2013

Checking environment variable in shell scripts

Found couple of ways, the common one :

My test scripts :


#!/bin/sh

if [ -n $JJ ] ; then

echo "-n1"
fi

if [ -z $JJ ] ; then

echo "-z1"
fi

JJ=""


if [ -n $JJ ]; then

echo "-n2"
fi

if [ -z $JJ ] ; then

echo "-z2"
fi

JJ="jcrys26"


if [ -n $JJ ]; then

echo "-n3"
fi

if [ -z $JJ ]; then

echo "-z3"
fi

The result is ...


-n1
-z1
-n2
-z2
-n3



-z to test if a string is empty.
-n to test is a string is not empty.

What about if a string is undefined? And the result really confused me. I have checked the environment variable, I don't have one with name of "JJ".

Reference : http://linuxcommand.org/wss0090.php

Have kept this in draft for a long long time due to the -n result. So.... A quick conclusion is, use the -z. Use -n at your own risk. To revisit this next time, if I still remember. :P



No comments:

Post a Comment