我想运行通过
&&
与 nohup 连接的多个命令。
命令的输出被重定向到 nohup.out
,这很好。但我想在两者之间发送一些消息到标准输出。这可能吗?
一个简单的例子如下:
nohup sh -c " \
echo some message 1 (to stdout) && \
some command 1 (to nohup.out) && \
echo some message 2 (to stdout) && \
some command 2 (to nohup.out) && \
..." &
我尝试将命令中的消息重定向到 stderr,然后将 stderr 重定向回 stdout:
nohup sh -c " \
echo some message 1 >&2 && \
some command 1 (to nohup.out) && \
echo some message 2 >$2 && \
some command 2 (to nohup.out) && \
..." 2>&1 &
但这对我不起作用。
有什么建议吗?
根据定义,
nohup
将任何输出重定向到nohup.out
。
一个简单的解决方法是写在其他地方,也许让你的 shell 显示“其他地方”的内容。
tail -f "$HOME"/.nohuplog &
nohup sh -c '
exec 3>>"$HOME"/.nohuplog
set -e # to avoid repeated "&&"
echo "some message 1" >&3
some command 1 (to nohup.out)
echo "some message 2" >&3
some command 2 (to nohup.out)
...' &
exec 3>...
这样你就可以使用>&3
而不必重复>>"$HOME"/.nohuplog
只是为了减少代码的重复性。
您可以使用 FIFO 代替文件等。
也许为了提高可用性,添加
trap
来解释脚本在出现错误时退出的原因。为此,Bash 为 ERR
提供了 trap
伪信号。