加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 09:22:33 所属栏目:安全 来源:网络整理
导读:假设我有以下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,
假设我有以下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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读