循环结束后循环时如何将输入输入到bash中并保留变量
BASH允许使用:cat<(echo“ $ filecontent”)
bash还允许使用:读取i时;做回声$ i;完成</etc/passwd
要结合上两个可以使用:echo $ filecontent |读书时;做回声$ i;完成
最后一个问题是它创建子壳,在while loop结束后变量i
无法再访问。
我的问题是:
如何实现这样的事情:<代码>阅读i;做回声$ i;完成&lt;(echo“ $ filecontent”)或换句话说:我如何确定i
在循环时生存?
请注意,我知道在语句中添加到{}
中时封闭,但这不能解决问题(想象一下您想在函数中使用wire loop并返回i
变量)
Bash allows to use: cat <(echo "$FILECONTENT")
Bash also allow to use: while read i; do echo $i; done </etc/passwd
to combine previous two this can be used: echo $FILECONTENT | while read i; do echo $i; done
The problem with last one is that it creates sub-shell and after the while loop ends variable i
cannot be accessed any more.
My question is:
How to achieve something like this: while read i; do echo $i; done <(echo "$FILECONTENT")
or in other words: How can I be sure that i
survives while loop?
Please note that I am aware of enclosing while statement into {}
but this does not solves the problem (imagine that you want use the while loop in function and return i
variable)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最快的是:
或一行:
The fastest was:
Or in one line:
Bash提供了VAR默认行为,因此:
这允许循环轻松捕获脚本和功能的stdin。
Bash provides var default behavior so:
This allows the loop to easily capture stdin, for scripts and functions.
“ http://www.gnu.org/software/software/bash/manual/manual/manual/bash.html#process-substitution”的正确符号
i 在循环终止时可用。
另一种选择是:
牙套是I/O分组操作,并且本身不会创建子壳。在这种情况下,它们是管道的一部分,因此作为子壳运行,但这是因为
|
而不是{...}
。您在问题中提到了这一点。 afaik,您可以在功能内部从这些内部进行返回。BASH还提供
shopt shopt
< < /a>内置及其众多选择之一是:因此,在脚本中使用类似的内容在循环后可用的
sum
:在命令行中进行此操作通常会犯规“工作控制不活动”(也就是说,在命令行中,作业控件处于活动状态)。在不使用脚本失败的情况下测试此操作。
另外,如 Gareth Rees 在他的答案,有时可以使用在这里字符串:
这不需要
shopt
;您可能可以使用它保存一个过程。The correct notation for Process Substitution is:
The last value of
i
assigned in the loop is then available when the loop terminates.An alternative is:
The braces are an I/O grouping operation and do not themselves create a subshell. In this context, they are part of a pipeline and are therefore run as a subshell, but it is because of the
|
, not the{ ... }
. You mention this in the question. AFAIK, you can do a return from within these inside a function.Bash also provides the
shopt
builtin and one of its many options is:Thus, using something like this in a script makes the modfied
sum
available after the loop:Doing this at the command line usually runs foul of 'job control is not active' (that is, at the command line, job control is active). Testing this without using a script failed.
Also, as noted by Gareth Rees in his answer, you can sometimes use a here string:
This doesn't require
shopt
; you may be able to save a process using it.jonathan leffler解释如何使用 process替换 ,但另一种可能性是使用
Jonathan Leffler explains how to do what you want using process substitution, but another possibility is to use a here string:
This saves a process.
此功能使重复$ num times jpg文件(bash)
This function makes duplicates $NUM times of jpg files (bash)