栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

为什么在bash的while读取循环内重定向stdin?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

为什么在bash的while读取循环内重定向stdin?

此处的明确意图是通过确保其stdin来自其他位置来防止

do_something
sample.text
流中读取。
如果没有看到重定向或不重定向的行为差异,那是因为
do_something
在测试中实际上没有从stdin读取数据。

如果您同时拥有两者

read
do_something
从同一流中读取内容,则
do_something
的后续实例将无法使用消耗的任何内容,
read
并且,当然,您将在输入到时输入非法内容
do_something
,从而导致诸如尝试使用错误的加密密钥(如果实际用例是
cryptmount
),&c。

cat sample.text | while read arg1 arg2 arg3 arg4 arg5; do    ret=0    do_something "$arg1" "$sarg2" "$arg3" "$arg4" "$arg5" <&3 || ret=$?done 3<&1

现在,它有很多错误-

3<&1
与相比是一种不好的做法
3<&0
,因为它假设没有基础就可以将stdout用作输入内容-但它 确实 可以实现该目标。


顺便说一下,我会这样写:

exec 3</dev/tty || exec 3<&0     ## make FD 3 point to the TTY or stdin (as fallback)while read -a args; do## |- loop over lines read from FD 0  do_something "${args[@]}" <&3  ## |- run do_something with its stdin copied from FD 3done <sample.text     ## -> ...while the loop is run with sample.txt on FD 0exec 3<&-  ## close FD 3 when done.

它有点冗长,需要显式关闭FD3,但这意味着如果我们将stdout连接到FIFO的只写侧(或任何其他只写接口)运行,我们的代码就不会再被破坏。而不是直接发送给TTY。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/408854.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号