且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-04 13:44:46

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

  echo中显示欢迎使用$(hostname)。祝您逗留愉快。 

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

  error + = $({./childScript.sh | sed的/输出/无用/'2>& 4 1>& 3;} 2>& 1) $'\n'


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 (..)

$(..) 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'