【问题标题】:Shell - Run additional command on failureShell - 在失败时运行附加命令
【发布时间】:2010-04-16 14:04:36
【问题描述】:

我目前正在运行这个脚本,它适用于除一个以外的所有实例:

 #!/bin/sh
 pdfopt test.pdf test.opt.pdf &>/dev/null
 pdf2swf test.opt.pdf test.swf
 [ "$?" -ne 0 ] && exit 2

上面的代码后面要执行更多的行...

如果“pdf2swf test.opt.pdf test.swf”失败,我将如何更改此脚本以运行“pdf2swf test.pdf test.swf”?如果第二次尝试失败,那么我会“exit 2”。

谢谢

【问题讨论】:

  • 这太快了,pdfopt 可能无法在pdf2swf 运行之前完成。让前一个块直到完成。

标签: linux bash shell command pdf2swf


【解决方案1】:

短路“OR”应该做你想做的事:

pdf2swf test.opt.pdf test.swf || pdf2swf test.pdf test.swf

【讨论】:

  • pdf2swf test.opt.pdf test.swf || pdf2swf test.pdf test.swf || exit 2
【解决方案2】:

试试:

/path/to/pdfopt test.pdf test.opt.pdf >/dev/null && {

    pdf2swf test.opt.pdf test.swf
    ... maybe do more stuff here, in the future ...
    exit_here_nicely
} 

code_that_is_reached_if_pdfopt_failed

在你的例子中:

pdfopt test.pdf test.opt.pdf &>/dev/null

...pdfopt 在后台运行,您不知道可能需要多长时间才能完成。让它阻塞,所以只有当它工作时才会到达括号中的代码。

一个可以在后台轻松启动的函数包装,但每个进程都会阻塞,直到第一个命令按预期退出。

【讨论】:

    【解决方案3】:

    也许你想要一个 Makefile 而不是 shell 脚本。如果其中一个命令失败,makefile 会自动中止。或者,您可以在每个命令后添加[ "$?" -ne 0 ] && exit 2

    【讨论】:

    • 如果没有两个目标的显式依赖关系,这将无法正常工作,如果它们缺乏,make -jxx 是有问题的。即使正确完成,它仍然是一个 shell 脚本,只是包装在一个 Makefile 中:)
    • OP 不是要求这样做还是认为这样做是成功的?所以这没有帮助。此外,如果您希望您的 shell 脚本在任何命令返回非零时退出,请使用 "#!/bin/sh -e" 而不是使用 makefile 或在每行之后写 'exit 2'。
    猜你喜欢
    • 2019-11-10
    • 2017-04-28
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 2012-10-09
    相关资源
    最近更新 更多