shell determines whether a variable is null
- 2021-01-02 22:07:28
- OfStack
How to determine whether a variable is empty in shell
In shell programming, the error check item for parameters contains whether to assign a variable (that is, whether a variable is null). The method to determine whether a variable is null is as follows:
1. Variables are enclosed in "" quotes
#!/bin/sh
para1=
if [ ! -n "$para1" ]; then
echo "IS NULL"
else
echo "NOT NULL"
fi
[Output] "IS NULL"
2. Judge directly by variables
#!/bin/sh
para1=
if [ ! $para1 ]; then
echo "IS NULL"
else
echo "NOT NULL"
fi
[Output] "IS NULL"
3. Use test
#!/bin/sh
dmin=
if test -z "$dmin"
then
echo "dmin is not set!"
else
echo "dmin is set !"
fi
[Output] "dmin is not set!
4. Use "" judgment
#!/bin/sh
dmin=
if [ "$dmin" = "" ]
then
echo "dmin is not set!"
else
echo "dmin is set !"
fi
[Output] "dmin is not set!"