Capture output from command into variable retainin

2019-06-14 00:10发布

问题:

I have two scripts; parentScript.sh and childScript.sh.

I want to be able to call childScript.sh inside parentScript.sh and return the errors that occur within at any stage. i.e. an error found within childScript.sh looks like:

echo "ERROR: Feed file missing for $siteTag" >&2

I know how to return the error out back towards the parent shell.

But I have a feeling it is being tampered with, I can no longer printf the result to a nice looking variable. i.e.

error+="$( { ./childScript.sh | sed 's/Output/Useless/' 2>&4 1>&3; } 2>&1 )"
error+="$( { ./childScript.sh | sed 's/Output/Useless/' 2>&4 1>&3; } 2>&1 )"

Should essentially call the script twice, get errors from both scripts and store them in the variable error as I thought, which it does but it somehow gets rid of the lines both with the use of echo "$error" or printf "$error".

Does anyone know a solution here to manage to grab error output from several commands but maintain the separate calls to echo within the childScript.sh commands?

Edit: Output should be..

ERROR: Feed file missing for (..)
ERROR: Feed file missing for (..)
ERROR: Feed file missing for (..)

But is instead

ERROR: Feed file missing for (..) ERROR: Feed file missing for (..) ERROR: Feed file missing for (..)

回答1:

$(..) strips trailing line feeds. This is very useful most of the time, like in

echo "Welcome to $(hostname). Enjoy your stay."

However, in your case, it ruins it a bit. You can just add one back:

error+="$( { ./childScript.sh | sed 's/Output/Useless/' 2>&4 1>&3; } 2>&1 )"$'\n'


标签: bash command