bash - 如何检测 bash 中可能包含空格的空字符串?

标签 bash

我想通过以下方式检测空字符串和白色字符串

#!/etc/bash

test_word=' ' # test_word includes only one space

if [[ ${test_word} =~ ^\s*$ ]]; then
  echo "detect"
else
  echo "not detect"
fi

结果是

not detect

它不起作用。 请让我知道如何检测它。 或者请让我知道一些选项,例如

if [[ -z ${var} ]]

最佳答案

\s 与 BASH 中的空格不匹配(它只匹配单个字母 s),您可以使用 POSIX 属性 [[:blank: ]] 匹配空格或制表符:

if [[ ${test_word} =~ ^[[:blank:]]*$ ]]; then
  echo "detect"
else
  echo "not detect"
fi

这是一种非正则表达式的检测方法:

if [[ -z ${test_word//[[:blank:]]/} ]]; then
    echo "detect"
else
    echo "not detect"
fi

${test_word//[[:blank:]]/} 将删除 $test_word 中的所有空格,而 -z 将删除检查给定字符串的长度是否为零。

这是另一种检测相同内容的extglob方法(感谢@gniourf_gniourf):

if [[ ${test_word} == *([[:blank:]]) ]]; then
    echo "detect"
else
    echo "not detect"
fi

关于bash - 如何检测 bash 中可能包含空格的空字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39545311/

相关文章:

mysql - 在 bash 脚本中存储 MySQL 密码

bash - 选择一个 vagrant provisioner

linux - 在 su 命令期间调用时如何隐藏密码?

扫描网络的Linux脚本

linux - 在 BASH 中使用 PIPESTATUS 有什么问题?

Linux 庆典 : Combine two csv files with different headers

mysql - 将 bash 变量应用于 mysql 插入语句 - 对某些人有效,但对其他人无效

linux - cat/dev/null 到多个文件以清除日志等现有文件

linux - 对两个字段进行排序。我想主要按字段 1 对文件进行排序,其次按字段 2(第二个字段需要按字典顺序排序)

linux - 将函数输出重定向到 printf 语句似乎在 bash 中不起作用