在显示实时输出的功能中执行命令 [英] Execute a command in a function displaying real-time output
问题描述
在某些Bash脚本中,我正在以这种方式执行一些保留实时输出的命令:
In some Bash scripts I am executing some commands preserving the real-time output in this way:
exec 5>&1
output=$(ls -1 2>&1 |tee /dev/fd/5; exit ${PIPESTATUS[0]})
status=$?
我将这段代码移到一个函数中,以使其可重用,如下所示:
I moved this piece of code in a function to make it reusable like this:
execute() {
# 1 - Execute backup
echo "Executing command 'very_long_command'..."
exec 5>&1
cmd="very_long_command"
output=$($cmd 2>&1 |tee /dev/fd/5; exit ${PIPESTATUS[0]})
status=$?
echo $output
echo "very_long_command exited with status $status."
return $status
}
当我使用 exec_output ="$(execute)"
调用该函数时,我当然可以获取其输出,但是我仍然需要获取 very_long_command
的输出.>在执行过程中,而不是在唯一输出末尾.
When I call the function with exec_output="$(execute)"
I can of course get its output, but what I still need is to get the output of very_long_command
during its execution, and not at the end in a unique output.
您能帮助我实现这一目标吗?
Could you help me to achieve this?
推荐答案
感谢 @Charles Duffy 我解决了我的问题,将FD 5重定向到stderr:
Thanks to @Charles Duffy I solved my problem, redirecting FD 5 to stderr:
execute() {
exec 5>&2
output=$(ls -1 2>&1 | tee /dev/fd/5; exit ${PIPESTATUS[0]})
status=$?
echo "$output"
return $status
}
output="$(execute)"
echo "Function output:"
printf "%s\n" "$output"
这篇关于在显示实时输出的功能中执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!