如果在文件末尾没有换行符,如何使用`while read`(Bash)读取文件中的最后一行?

前端之家收集整理的这篇文章主要介绍了如果在文件末尾没有换行符,如何使用`while read`(Bash)读取文件中的最后一行?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有以下Bash脚本:
while read SCRIPT_SOURCE_LINE; do
  echo "$SCRIPT_SOURCE_LINE"
done

我注意到,对于没有换行符的文件末尾,这将有效地跳过最后一行。

搜索了一个解决方and found this

When read reaches end-of-file instead
of end-of-line,it does read in the
data and assign it to the variables,
but it exits with a non-zero status.
If your loop is constructed “while
read ;do stuff ;done

So instead of testing the read exit
status directly,test a flag,and have
the read command set that flag from
within the loop body. That way
regardless of reads exit status,the
entire loop body runs,because read
was just one of the list of commands
in the loop like any other,not a
deciding factor of if the loop will
get run at all.

06001

我如何重写这个解决方案,使它的行为完全一样的while循环我早些时候,即没有硬编码的输入文件的位置?

在你的第一个例子中,我假设你正在从stdin读取。要做与第二个代码块相同,你只需要删除重定向和echo $ REPLY:
DONE=false
until $DONE ;do
read || DONE=true
echo $REPLY
done
原文链接:https://www.f2er.com/bash/390003.html

猜你在找的Bash相关文章