To check if a variable is set or empty, we can use couple of approaches. One approach is to use empty string check (if [ -z $string]) . This approach is little inaccurate but will work in most cases. Better approach is to use parameter substitution (${var+val}) and then empty string check (if [ -z $string]).
Parameter substitution using ${var+val}
If variable var is set then use val otherwise null.
#!/bin/bash
var=somethings
echo ${var+val}val
Env: GNU bash, version 4.2.46
Bash code – check if a variable is set
Here empty string will be considered as set.
#!/bin/bash
if [ -z ${var+x} ]; then
echo "variable var is not set"
else
echo "variable var is set"
fi
var=""
if [ -z ${var+x} ]; then
echo "variable var is not set"
else
echo "variable var is set"
fivariable var is not set variable var is set
Env: GNU bash, version 4.2.46
${var+x} we can use any string in place of x.