我正在尝试运行以下 shell 脚本,该脚本应该检查字符串是否既不是空格也不是空。但是,对于所有提到的 3 个字符串,我得到了相同的输出。我也尝试过使用“[[”语法,但没有成功。
这是我的代码:
str="Hello World"
str2=" "
str3=""
if [ ! -z "$str" -a "$str"!=" " ]; then
echo "Str is not null or space"
fi
if [ ! -z "$str2" -a "$str2"!=" " ]; then
echo "Str2 is not null or space"
fi
if [ ! -z "$str3" -a "$str3"!=" " ]; then
echo "Str3 is not null or space"
fi
我得到以下输出:
# ./checkCond.sh
Str is not null or space
Str2 is not null or space
您需要在
!=
的两侧留出一个空间。将您的代码更改为:
str="Hello World"
str2=" "
str3=""
if [ ! -z "$str" -a "$str" != " " ]; then
echo "Str is not null or space"
fi
if [ ! -z "$str2" -a "$str2" != " " ]; then
echo "Str2 is not null or space"
fi
if [ ! -z "$str3" -a "$str3" != " " ]; then
echo "Str3 is not null or space"
fi
用于检查 shell 中的空字符串
if [ "$str" = "" ];then
echo NULL
fi
或
if [ ! "$str" ];then
echo NULL
fi
另一个快速测试字符串是否包含除空格之外的内容。
if [[ -n "${str// /}" ]]; then
echo "It is not empty!"
fi
“-n”表示非零长度字符串。
那么前两个斜杠意味着匹配以下内容的all,在我们的例子中是空格。然后第三个斜杠后面跟着替换(空)字符串,并以“}”结束。请注意与通常的正则表达式语法的区别。
您可以在此处阅读有关 bash shell 脚本中的字符串操作的更多信息。
如果您需要检查任意数量的空格,而不仅仅是单个空格,您可以这样做:
去除字符串中多余的空格(也将中间的空格压缩为一个空格):
trimmed=`echo -- $original`
--
确保如果$original
包含 echo 可以理解的开关,它们仍然会被视为要回显的正常参数。另外,重要的是不要将 ""
放在 $original
周围,否则空格将不会被删除。
之后你可以检查
$trimmed
是否为空。
[ -z "$trimmed" ] && echo "empty!"
要检查字符串是否为空或仅包含空格,可以使用:
shopt -s extglob # more powerful pattern matching
if [ -n "${str##+([[:space:]])}" ]; then
echo '$str is not null or space'
fi
请参阅 Bash 手册中的 Shell 参数扩展 和 模式匹配 。
[ $(echo $variable_to_test | sed s/\n// | sed s/\ //) == "" ] && echo "String is empty"
从字符串中删除所有换行符和空格将导致空白字符串被减少为可以测试和操作的空白