The following bash script example we show some of the way how to check for an empty or null variable using bash:
#!/bin/bash 

if [ -z "$1" ]; then
    echo "Empty Variable 1"
fi


if [ -n "$1" ]; then
    echo "Not Empty Variable 2"
fi


if [ ! "$1" ]; then
    echo "Empty Variable 3"
fi


if [ "$1" ]; then
    echo "Not Empty Variable 4"
fi


[[ -z "$1" ]] && echo "Empty Variable 5" || echo "Not empty Variable 5"
Save the above script into eg. check_empty.sh and execute with our without command line arguments:
$ bash check_empty.sh 
Empty Variable 1
Empty Variable 3
Empty Variable 5
Furthermore, the execution of the above script with a command line argument will trigger opposite results:
$ bash check_empty.sh hello
Not Empty Variable 2
Not Empty Variable 4
Not empty Variable 5
ARE YOU LOOKING FOR A LINUX JOB?
Submit your RESUME, create a JOB ALERT or subscribe to RSS feed on LinuxCareers.com.
LINUX CAREER NEWSLETTER
Subscribe to NEWSLETTER and receive latest news, jobs, career advice and tutorials.
DO YOU NEED ADDITIONAL HELP?
Get extra help by visiting our LINUX FORUM or simply use comments below.

You may also be interested in: