在某些Bash脚本中,我正在以这种方式执行一些命令以保留实时输出:
exec 5>&1
output=$(ls -1 2>&1 |tee /dev/fd/5; exit ${PIPESTATUS[0]})
status=$?
我将这段代码移到一个函数中,以使其可重用,如下所示:
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
的输出,而不是最后获得唯一的输出。输出。
您能帮助我实现这一目标吗?
答案 0 :(得分:3)
感谢 @Charles Duffy ,我解决了我的问题,将FD 5重定向到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"