在失败的管道杀下一个命令(击) [英] Kill next command in pipeline on failure (Bash)
问题描述
我有我运行一个流式备份脚本如下:
I have a streaming backup script which I'm running as follows:
./backup_script.sh | aws s3 cp - s3://bucket/path/to/backup
的 AWS
命令流标准输入到云存储在原子的方式。如果过程没有EOF中断,上传被中止。
The aws
command streams stdin to cloud storage in an atomic way. If the process is interrupted without an EOF, the upload is aborted.
我要的 AWS
过程中被杀死,如果 ./ backup_script.sh
退出以非零退出code。
I want the aws
process to be killed if ./backup_script.sh
exits with a non-zero exit code.
任何bash的把戏这样做?
Any bash trick for doing this?
编辑:
你可以用这个脚本测试您的解决方案:
You can test your solution with this script:
#!/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"
例如:
$ 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
我想 ./ sigoreof.py
与信号终止。
推荐答案
它使用进程替换,而不是命名管道的一个简短的脚本是:
A short script which uses process substitution instead of named pipes would be:
#!/bin/bash
exec 4> >( ./second-process.sh )
./first-process.sh >&4 &
if ! wait $! ; then echo "error in first process" >&2; kill 0; wait; fi
它与一个FIFO很像,基本上都采用的FD作为IPC而不是文件名的信息载体。
It works much like with a fifo, basically using the fd as the information carrier for the IPC instead of a file name.
二话:我不知道是否有必要关闭FD 4;我会假设,在脚本退出外壳关闭所有打开的文件。
Two remarks: I wasn't sure whether it's necessary to close fd 4 ; I would assume that upon script exit the shell closes all open files.
和我无法弄清楚如何获得进程的PID的过程中替换(别人吗?至少在我的cygwin通常的 $!
没的工作。)因此,我使出了组,这可能不是理想地杀死所有进程(但我不能完全肯定的语义)。
And I couldn't figure out how to obtain the PID of the process in the process substitution (anybody? at least on my cygwin the usual $!
didn't work.) Therefore I resorted to killing all processes in the group, which may not be desirable (but I'm not entirely sure about the semantics).
这篇关于在失败的管道杀下一个命令(击)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!