How to Test Null Unix Script
Shell scripts are a powerful way of manipulating data and commands within the Unix operating system. Null variables are difficult to test, unless you know the correct way of doing this. In other languages, variables containing things like "" normally classed as null are not in the case of the Unix shell as they are interpreted differently. Having null values in variables is often a useful indicator of problems occurring in a script when values are not assigned automatically as expected. When this occurs action can be taken and problems rectified or the script can take an entirely different route to solve the problem.
Instructions
-
-
1
Ensure that the variable to test is NOT set to anything. A simple way to do this is to test a variable that has not been assigned to a value prior to the test, by not initializing the variable such as var="". In this example, "" would be classed as a string (not actually zero length) and would be interpreted as a value in shell script.
-
2
Test the variable for zero length using the standard Unix shell syntax which (in the Bourne shell version) is:
if [ -z "$var" ]
then
# other commands ...
fi
This means if the "$var" variable does not have a length, it is a null value. Action can then be taken based on the test in the "then" statement which follows.
-
-
3
Test a variable for a null value, and if it does not contain a value, assign one in a single command. This can be achieved by using a special shell command as follows:
varisnullornot=${var:-NULL}
In this case the "varisnullornot" variable will be assigned the value contained in the variable "var" if it has a value. If it does not have a value then the variable "varisnullornot" will be assigned the word "NULL," which can then be tested as follows:
if [ "$varisnullornot"="NULL" ]
then
echo "Var is a null variable"
else
echo "\"varisnullornot\"" is assigned the value contained in \"var\""
fi
-
1
Tips & Warnings
The "test" command varies by different shell, including the Bourne shell, Kshell, Cshell and others. Please consult the man page of your version by typing "man test" in the command line of the shell you are using.