在shell脚本中,如何判断输入变量或参数是否为空,五种判断shell变量或参数空值的方法,包括shell判断变量、shell判断输入参数、使用test判断等方式。
shell判断参数或变量是否为空的五种方法(shell条件判断)
1,shell判断变量
复制代码 代码示例:
read -p "input a word :" word
if [ ! -n "$word" ] ;then
echo "you have not input a word!"
else
echo "the word you input is $word"
fi
2,shell判断输入参数
复制代码 代码示例:
#!/bin/bash
if [ ! -n "$1" ] ;then
echo "you have not input a word!"
else
echo "the word you input is $1"
fi
以下未验证。
3,直接通过变量判断
结果为: IS NULL
复制代码 代码示例:
#!/bin/sh
para1=
if [ ! $para1 ]; then
echo "IS NULL"
else
echo "NOT NULL"
fi
4,使用test判断
结果: dmin is not set!
复制代码 代码示例:
#!/bin/sh
dmin=
if test -z "$dmin"
then
echo "dmin is not set!"
else
echo "dmin is set !"
fi
5,使用""判断
复制代码 代码示例:
#!/bin/sh
dmin=
if [ "$dmin" = "" ]
then
echo "dmin is not set!"
else
echo "dmin is set !"
fi
shell脚本,用在系统启动时:
复制代码 代码示例:
#! /bin/bash
echo "Input Param Is [$1]"
if [ ! -n "$1" ] ;then
echo "you have not input a null word!"
./app1;./app12;./app123
elif [ $1 -eq 2 ];then
./app12;./app123
elif [ $1 -eq 90 ];then
echo "yy";
fi