Linux 测试字符串在 Bash 中是否有非空白字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9767644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:15:20  来源:igfitidea点击:

Test if string has non whitespace characters in Bash

linuxstringbashif-statementcomparison

提问by Yamiko

My script is reading and displaying id3 tags. I am trying to get it to echo unknown if the field is blank but every if statement I try will not work. The id3 tags are a fixed size so they are never null but if there is no value they are filled with white space. I.E the title tag is 30 characters in length. Thus far I have tried

我的脚本正在读取和显示 id3 标签。如果该字段为空白,我试图让它回显未知,但我尝试的每个 if 语句都不起作用。id3 标签的大小是固定的,所以它们永远不会为空,但如果没有值,它们会用空格填充。IE 标题标签的长度为 30 个字符。到目前为止我已经尝试过

echo :$string: #outputs spaces between the 2 ::

echo :$string: #outputs spaces between the 2 ::

if [ -z "$string" ] #because of white space will always evaluate to true

if [ -z "$string" ] #because of white space will always evaluate to true

x=echo $string | tr -d ' '; if [ -z "$string" ];#still evaluates to true but echos :$x: it echos ::

x=echo $string | tr -d ' '; if [ -z "$string" ];#still 评估为真但回声 :$x: 它回声 ::

the script

剧本

#!bin/bash
echo "$# files";
while [ "$i" != "" ];
do
   TAG=`tail -c 128 "$i" | head -c 3`;
   if [ $TAG="TAG" ]
   then
      ID3[0]=`tail -c 125 "" | head -c 30`;
      ID3[1]=`tail -c 95 "" | head -c 30`;
      ID3[2]=`tail -c 65 "" | head -c 30`;
      ID3[3]=`tail -c 35 "" | head 4`;
      ID3[4]=`tail -c 31 "$i" | head -c 28`;
      for i in "${ID3[@]}"
      do
         if [ "$(echo $i)" ] #the if statement mentioned
         then
            echo "N/A";
         else
            echo ":$i:";
         fi
      done
   else
      echo "$i does not have a proper id3 tag";
   fi
   shift;
done

采纳答案by Peter.O

You can use bash's regex syntax.

您可以使用 bash 的正则表达式语法。

It requires that you use double square brackets [[ ... ]], (more versatile, in general).
The variable does not need to be quoted. The regex itself must notbe quoted

它要求您使用双方括号[[ ... ]], (通常更通用)。
变量不需要被引用。不得引用 正则表达式本身

for str in "         "  "abc      " "" ;do
    if [[ $str =~ ^\ +$ ]] ;then 
      echo -e "Has length, and contain only whitespace  \"$str\"" 
    else 
      echo -e "Is either null or contain non-whitespace \"$str\" "
    fi
done

Output

输出

Has length, and contain only whitespace  "         "
Is either null or contain non-whitespace "abc      " 
Is either null or contain non-whitespace "" 

回答by ams

if [ "$(echo "$string" | tr -s ' ')" == " " ]; then
  echo "all white space"
fi

That compresses all repeated spaces down to one space, and compares for that.

这将所有重复的空格压缩为一个空格,并进行比较。

回答by Micha? Politowski

A non-bash specific, shell only variant:

一个非 bash 特定的、仅限 shell 的变体:

case "$string" in
 *[!\ ]*) echo "known";;
 *) echo "unknown";;
esac

回答by Eugene Yarmash

With extended globs enabled (shopt -s extglob):

启用扩展 globs ( shopt -s extglob):

if [ -n "${string##+([[:space:]])}" ]; then
    echo '$string has non-whitespace characters'
fi

回答by alian

This one checks for Zero length or SPACE or TAB

这个检查零长度或空格或制表符

S="Something"
if [[ "x$S" == "x" || "x$S" == x*\ * || "x$S" == x*\    * ]] ;then
  echo "Is not OK"
else
  echo "Is OK"
fi

回答by Charles Duffy

Many of these answers are far more complex, or far less readable, than they should be.

其中许多答案比应有的要复杂得多,或者可读性要差得多。

[[ $string = *[[:space:]]* ]]  && echo "String contains whitespace"
[[ $string = *[![:space:]]* ]] && echo "String contains non-whitespace"

回答by Peter Steier

[[ -z `echo $string` ]]

The backquotes execute the command within; bash line parsing convert tabs and newlines to blanks and joins double blanks. The echo command re-emits this string, which is shrunk to an empty string for the final test by [[ ]]. I think this is the shortest solution which passes the following:

反引号执行其中的命令;bash 行解析将制表符和换行符转换为空格并连接双空格。echo 命令重新发出此字符串,该字符串通过 [[ ]] 缩小为空字符串以进行最终测试。我认为这是通过以下的最短解决方案:

> VAR="$(echo -e " \n\t")"
> [[ -z  `echo $VAR` ]] ; echo $?
0
> VAR="$(echo -e " \na\t")"
> [[ -z  `echo $VAR` ]] ; echo $?
1
> VAR="$(echo -e "aaa bbb")"
> [[ -z  `echo $VAR` ]] ; echo $?
1
> VAR=
> [[ -z  `echo $VAR` ]] ; echo $?
0

回答by MrPotatoHead

Sharing a more portable method not requiring double-brackets [[ ]] while keeping it simple, as much as possible.

分享一种更便携的方法,不需要双括号 [[]],同时尽可能保持简单。

Detect a string containing ONLY white space or = null:

检测仅包含空格或 = null 的字符串:

if [ -z "${string// }" ]; then <do something>; fi

Which in this case would be:

在这种情况下将是:

${var// }

Such as:

如:

if [ -z "${string// }" ]; then echo "It's empty!"; fi

What this does is simply replace all white space with null through substitution. If $string contains only white space, the -z test will evaluate TRUE. If there are non-white space characters in the string, the equation evaluates to FALSE.

这样做只是通过替换将所有空白替换为 null。如果 $string 仅包含空格,则 -z 测试将评估为 TRUE。如果字符串中存在非空白字符,则等式的计算结果为 FALSE。

Elaborating further on BASH (since OP asked about this in BASH), the example above will not catch tabs, though it is possible to do so. Here are more examples in BASH that do and don't work as expected.

进一步详细说明 BASH(因为 OP 在 BASH 中询问了这一点),上面的示例不会捕获选项卡,尽管可以这样做。以下是 BASH 中按预期工作和不工作的更多示例。

Let's say there's a tab in the search string.

假设搜索字符串中有一个选项卡。

This works:

这有效:

string=$(echo -e "\t"); if [ -z ${string// } ]; then echo "It's empty!"; fi

But these don't:

但这些没有:

string=$(echo -e "\t"); if [ -z "${string// }" ]; then echo "It's empty!"; fi
string=$(echo -e "\t"); if [ -z '${string// }' ]; then echo "It's empty!"; fi

The two last examples above both report the string is not empty. If you consider a tab to be white space, that would be a problem and you'd want to use the first example.

上面的最后两个示例都报告字符串不为空。如果您将制表符视为空白,那将是一个问题,您会想要使用第一个示例。

What about newline? Let's take a look at an \nscenario. First off, "correct" behavior depends on your expectations.

换行呢?我们来看一个\n场景。首先,“正确”行为取决于您的期望。

These treat newlines (\n) as white space (equation evaluates TRUE):

这些将换行符 ( \n) 视为空格(等式计算为 TRUE):

string=$(echo -e "\n\n"); if [ -z ${string// } ]; then echo "It's empty!"; fi
string=$(echo -e "\n\n"); if [ -z "${string// }" ]; then echo "It's empty!"; fi

This doesn't (equation evaluates to FALSE), meaning this equation thinks a newline is not white space.

这不是(等式评估为 FALSE),这意味着该等式认为换行符不是空格。

string=$(echo -e "\n\n"); if [ -z '${string// }' ]; then echo "It's empty!"; fi

If you require checking for newlines and tabs and spaces, you may need to use two IF/THEN statements or the CASE method described above.

如果您需要检查换行符、制表符和空格,您可能需要使用两个 IF/THEN 语句或上述 CASE 方法。