开发者

capture output from a pipe and store it in a variable

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜