捕获管道的输出并将其存储在变量中
我正在尝试捕获管道的输出并将其存储在变量中。使用子shell即var=$(computeOutput)将不起作用,因为computeOutput函数本身正在设置需要存储在与输出相同范围内的其他变量。如果我使用子 shell,其他变量将在子 shell 的本地副本中设置,但不会在父 shell 中设置。
我想到的一种解决方案如下:
给定函数...
function storeOutput() { var=$(猫) ...
当我执行以下操作时...
echo "hello" |存储输出; echo $var
...“hello”,var 的值,打印在控制台上
但是,当我从脚本内部使用此函数而不是获得正确的结果时,我得到了当前目录内容的列表。仅供参考,我正在使用安装了 mac ports 的 mac OSX。
谁能解释为什么会发生这种情况???或者更好地建议另一个解决方案
I am trying to capture output from a pipe and store it in a variable. Using a subshell ie var=$(computeOutput) WILL NOT WORK because the computeOutput function itself is setting other variables that need to be stored in the same scope as the output. If I use a subshell the other variables will be set in the subshell's local copy but not in the parent shell.
One solution I thought of is the following:
Given the function...
function storeOutput() {
var=$(cat)
}
...when I do the following...
echo "hello" | storeOutput; echo $var
... "hello", the value of var, is printed on the console
However when I use this function from inside a script instead of getting the correct result I get a listing of the contents of the current directory. FYI I am using mac OSX with mac ports installed.
Can anyone explain why this is happening??? OR BETTER STILL SUGGEST ANOTHER SOLUTION
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题已解决:在脚本中,我将多行输出通过管道传输到 storeOutput 函数。当我打印 var 的值时,我忘记将它括在双引号中,即“$var”,因此假设它将输出的一部分视为命令,例如 ls
除了函数 storeOutput() { var=$(cat ) } 似乎有效
Problem solved: In the script I was piping multi-line output to the storeOutput function. When I printed the value of var I forgot to enclose it in double quotes, ie "$var" so assume it regarded part of the output as a command, such as ls
Other than that the function storeOutput() { var=$(cat) } seems to work