Friday, August 15, 2008

How to check if environment variable is defined or not in Unix?

Suppose, I want to check if variable USER_ID is defined or not.

---------------------------------------------------------------

The best solution I found is:



NOTDEFINED=ItsUnDefined

USER_ID=${USER_ID:-$NOTDEFINED}



if [ "$USER_ID" = "ItsUnDefined" ]

then

echo Enter USER ID:

read USER_ID

fi

echo USER_ID



Explanation: USER_ID=${USER_ID:-$NOTDEFINED}

This will check if USER_ID variable is defined or not. If it is undefined, it will assign value of variable NOTDEFINED to it otherwise it will use its own value.



Generally we use this to see if user has passed command line parameters. And if user has not passed parameter, you can set default value using this.

USER_ID=${1:-arpit}

echo $USER_ID

---------------------------------------------------------------

The second solution can be used is:



envgrep "^USER_ID"

if [ $? -eq 1 ]

then

echo Enter USER ID:
read USER_ID
fi
echo USER_ID



Explanation: env lists all environment variables defined for the shell. Then you can grep to see, if the variable is defined or not.



---------------------------------------------------------------