在失败时杀死管道中的下一个命令

omr*_*umi 7 bash

我有一个流式备份脚本,我正在运行如下:

./backup_script.sh | aws s3 cp - s3://bucket/path/to/backup
Run Code Online (Sandbox Code Playgroud)

aws命令以原子方式将stdin流式传输到云存储.如果在没有EOF的情况下中断进程,则上载将中止.

aws如果./backup_script.sh使用非零退出代码退出,我希望该进程被终止.

这样做的任何bash技巧?

编辑:您可以使用此脚本测试您的解决方案:

#!/usr/bin/env python
import signal
import sys
import functools

def signal_handler(signame, signum, frame):
    print "Got {}".format(signame)
    sys.exit(0)

signal.signal(signal.SIGTERM, functools.partial(signal_handler, 'TERM'))
signal.signal(signal.SIGINT, functools.partial(signal_handler, 'INT'))

for i in sys.stdin:
    pass

print "Got EOF"
Run Code Online (Sandbox Code Playgroud)

例:

$ grep --bla | ./sigoreof.py
grep: unrecognized option `--bla'
usage: grep [-abcDEFGHhIiJLlmnOoqRSsUVvwxZ] [-A num] [-B num] [-C[num]]
    [-e pattern] [-f file] [--binary-files=value] [--color=when]
    [--context[=num]] [--directories=action] [--label] [--line-buffered]
    [--null] [pattern] [file ...]
Got EOF
Run Code Online (Sandbox Code Playgroud)

我希望./sigoreof.py被一个信号终止.

Pet*_*ica 2

使用进程替换而不是命名管道的简短脚本如下:

#!/bin/bash

exec 4> >( ./second-process.sh )
./first-process.sh >&4  &
if ! wait $! ; then echo "error in first process" >&2; kill 0; wait; fi
Run Code Online (Sandbox Code Playgroud)

它的工作原理很像fifo,基本上使用fd而不是文件名作为IPC的信息载体。

两点评论:我不确定是否有必要关闭 fd 4 ;我假设脚本退出后 shell 会关闭所有打开的文件。

而且我不知道如何在进程替换中获取进程的PID(有人吗?至少在我的cygwin上通常$!不起作用。)因此我诉诸于杀死组中的所有进程,这可能不是理想的(但我不完全确定语义)。