将命令的输出捕获到保留新行的变量中

Capture output from command into variable retaining new lines

我有两个脚本; parentScript.shchildScript.sh.

我希望能够在 parentScript.sh 和 return 中调用 childScript.sh 在任何阶段发生的错误。即在 childScript.sh 中发现的错误看起来像:

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

我知道如何return the error out back towards the parent shell.

但我感觉它被篡改了,我无法再将结果 printf 转换为一个漂亮的变量。即

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 )"

基本上应该调用脚本两次,从两个脚本中获取错误并将它们存储在变量 error 中,正如我所想的那样,但它以某种方式摆脱了使用 echo "$error"printf "$error".

有谁知道这里的解决方案来设法从多个命令中获取错误输出,但在 childScript.sh 命令中保持对 echo 的单独调用?

编辑:输出应该是..

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

而是

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

$(..) 去除尾随换行符。这在大多数时候都非常有用,例如

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

但是,在你的情况下,它有点毁了它。你可以只加一个回来:

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