gpt4 book ai didi

Bash 脚本,执行命令,在每一行前加上给定的字符串

转载 作者:行者123 更新时间:2023-11-29 09:17:27 26 4
gpt4 key购买 nike

假设我有一个如下所示的 bash 脚本:

#!/bin/bash
echo "start"
do something
git merge blah blah
ant build.xml blah blah blah
echo "end"

很明显,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

万一某个伟大的人有解决方案,我还有另一个小问题,即使绝对不那么重要。

如果行太长,我还可以拆分命令输出吗?这是为了避免类似的事情

[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

正如我想你注意到的,我正在尝试整理我的 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

@Yoory当我尝试集成该功能时,将其放在 git 命令之前,PIPESTATUS 总是返回 0,即使 git merge 失败,我确信找到解决方案并不难,但正如您所见,我'对 bash 不是很熟练。

所以现在我正在使用简单的 sed:| sed 's/^/[GIT]/' 或 | sed 's/^/[ANT]/'我尝试将 fmt 与 sad 进行简单的管道集成。

command | fmt -w 20 | sed "s/^/[ANT] /"

问题是它适用于带有普通句子的日志,但它不适用于没有空格分隔符的长字符串(例如路径),因为看起来 fmt 不会像我使用的那样破坏它,我正在看着那个人找到一个可以帮助我的参数,但我认为直到现在我都无法实现。

我确实设法让它与 fmt 一起工作,但 fold 对我来说很神奇!

 command | fold -w 138 | sed "s/^/[ANT] /" 

感谢大家的帮助,如果您想添加任何反馈,我希望听到他们的意见,编码并学习!

最佳答案

想到的第一个解决方案:

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]}
}

这样使用:

prefix_output git merge blah blah
prefix_output ant build.xml blah blah blah

同时更新的版本现在尊重执行命令的返回状态。以下将起作用:

prefix_output git merge blah blah && echo success || echo failure

为了解决换行太长的问题,有一个使用 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]}
}

我已经用简单的命令对其进行了测试,请告诉我它是否不适用于一些更复杂的情况。

关于Bash 脚本,执行命令,在每一行前加上给定的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47773196/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com