将命令的输出捕获到保留新行的变量中 [英] Capture output from command into variable retaining new lines

查看:66
本文介绍了将命令的输出捕获到保留新行的变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



I希望能够在 parentScript.sh 内调用 childScript.sh 并返回在任何阶段发生的错误。即在 childScript.sh 中发现的错误如下:

  echo错误:缺少$ siteTag的供稿文件& 2 

我知道如何返回错误 out 回到父外壳。



但是我感觉它被篡改了,我不能再 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 的单独调用? p>

编辑:输出应为..

 错误:缺少供稿文件(..)
错误:(..)
错误的Feed文件:(..)

但是相反

  ER ROR:供稿文件缺少(..)错误:供稿文件缺少(..)错误:供稿文件缺少(..)


解决方案

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

  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'

这篇关于将命令的输出捕获到保留新行的变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆