bash 如何测试shell脚本中的行是否为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2578116/
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-09-09 19:08:49  来源:igfitidea点击:

How can I test if line is empty in shell script?

bashshellsh

提问by planetp

I have a shell script like this:

我有一个这样的shell脚本:

cat file | while read line
do
    # run some commands using $line    
done

Now I need to check if the line contains any non-whitespace character ([\n\t ]), and if not, skip it. How can I do this?

现在我需要检查该行是否包含任何非空白字符 ([\n\t ]),如果没有,请跳过它。我怎样才能做到这一点?

回答by Arkku

Since readreads whitespace-delimited fields by default, a line containing only whitespace should result in the empty string being assigned to the variable, so you should be able to skip empty lines with just:

由于read默认情况下读取以空格分隔的字段,因此仅包含空格的行应该会导致将空字符串分配给变量,因此您应该能够跳过空行,只需:

[ -z "$line" ] && continue

回答by NSC

try this

尝试这个

while read line;
do 

    if [ "$line" != "" ]; then
        # Do something here
    fi

done < $SOURCE_FILE

回答by Ignacio Vazquez-Abrams

bash:

重击:

if [[ ! $line =~ [^[:space:]] ]] ; then
  continue
fi

And use done < fileinstead of cat file | while, unless you know why you'd use the latter.

并使用done < file代替cat file | while,除非您知道为什么要使用后者。

回答by Ignacio Vazquez-Abrams

if ! grep -q '[^[:space:]]' ; then
  continue
fi

回答by ghostdog74

cati useless in this case if you are using while read loop. I am not sure if you meant you want to skip lines that is empty or if you want to skip lines that also contain at least a white space.

cat如果您使用 while 读取循环,我在这种情况下没用。我不确定您的意思是要跳过空行还是要跳过至少还包含空格的行。

i=0
while read -r line
do
  ((i++)) # or $(echo $i+1|bc) with sh
  case "$line" in
    "") echo "blank line at line: $i ";;
    *" "*) echo "line with blanks at $i";;
    *[[:blank:]]*) echo "line with blanks at $i";;
  esac
done <"file"

回答by Rounak

blank=`tail -1 <file-location>`
if [ -z "$blank"  ]
then
echo "end of the line is the blank line"
else
echo "their is something in last line"
fi