如果在文件末尾没有换行符,如何使用`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

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...