我们假设我有一个类似下面的bash脚本:
#!/bin/bash
echo "start"
do something
git merge blah blah
ant build.xml blah blah blah
echo "end"
Run Code Online (Sandbox Code Playgroud)
显然,git和ant命令的输出与任何其他echo一样包含在bash输出中.
有没有办法实现类似下面的东西?
start
i'm doing something
[GIT] git command output
[GIT] git command output
[GIT] git command output
[GIT] git command output
[ANT] ant command output
[ANT] ant command output
[ANT] ant command output
[ANT] ant command output
[ANT] ant command output
end
Run Code Online (Sandbox Code Playgroud)
如果一个伟大的人有一个解决方案,我还有一个小问题,即使绝对不那么重要.
如果线路太长,我还可以拆分命令输出吗? 这样可以避免类似的事情
[ANT] ant command output too long command output too long command output too
long command output too long command output too long
[ANT] ant command output
[ANT] ant command output
Run Code Online (Sandbox Code Playgroud)
我认为你注意到我正在尝试整理我的shell的输出,它们是通过Jenkins启动的,并由一个常规的管道脚本生成.
@Yoory&@ghoti:
谢谢两位,答案很可爱!
这个功能很棒,但遗憾的是我整合起来有点困难,因为它必须与其他两个东西进行交互,这使得它有点难以阅读和混淆.在确切的代码下方,对不起,如果我之前没有说过:
git merge --no-ff origin/module 2>&1 | tee -a /merge_files/merge.log
if [ "${PIPESTATUS[0]}" -ne "0" ];
then
something
else
other to do..
fi
Run Code Online (Sandbox Code Playgroud)
@Yoory 当我尝试集成该函数时,将它放在git命令之前,即使git merge失败,PIPESTATUS也总是返回0,我确定找到它的解决方案并不是那么难,但是你可以看到我对bash不熟悉.
所以现在我正在使用简单的sed:| sed's/^/[GIT] /'或| sed's/^/[ANT] /'我试图整合fmt,简单地将它与悲伤相连.
command | fmt -w 20 | sed "s/^/[ANT] /"
Run Code Online (Sandbox Code Playgroud)
问题是它适用于具有普通句子的日志,但它不适用于没有空格分隔符的长字符串(例如路径)导致看起来像fmt不会像我使用的那样打破它,我正在看男人找到一个可以帮助我的参数,但我认为直到现在我都无法实现.
我确实设法让它与fmt一起工作,但折叠为我带来了魔力!
command | fold -w 138 | sed "s/^/[ANT] /"
Run Code Online (Sandbox Code Playgroud)
感谢大家的帮助,如果您想添加任何反馈,我希望听到他们,编码和学习!
想到的第一个解决方案:
function prefix_output {
local prefix=$1
prefix=${prefix^^}
"${@}" 2>&1 | while read -r line; do
printf "[%s] %s\n" "${prefix}" "${line}"
done
return ${PIPESTATUS[0]}
}
Run Code Online (Sandbox Code Playgroud)
使用这种方式:
prefix_output git merge blah blah
prefix_output ant build.xml blah blah blah
Run Code Online (Sandbox Code Playgroud)
此外,更新版本现在尊重已执行命令的返回状态.以下将有效:
prefix_output git merge blah blah && echo success || echo failure
Run Code Online (Sandbox Code Playgroud)
为了解决包装太长的行,有一个使用的修改版本fmt(受其他人的答案启发):
function prefix_output {
local prefix=$1
prefix=${prefix^^}
"${@}" 2>&1 | fmt -w 80 | while read -r line; do
printf "[%s] %s\n" "${prefix}" "${line}"
done
return ${PIPESTATUS[0]}
}
Run Code Online (Sandbox Code Playgroud)
我已经在简单的命令上测试了它,告诉我它是否适用于一些更复杂的情况.