Bash:确保在使用set -euo pipefail时始终运行命令

时间:2018-03-02 21:17:50

标签: bash

我正在用Bash编写一个看起来像这样的脚本:

LOOP AT itab_budat ASSIGNING <line_budat>.
  MODIFY itab FROM itab USING KEY by_doc_key TRANSPORTING budat
       WHERE bukrs = <line_budat>-bukrs
         AND belnr = <line_budat>-belnr
         AND gjahr = <line_budat>-gjahr.
ENDLOOP.

我想要做的是确保在脚本结束时始终调用#!/usr/bin/env bash # Stop the script if any commands fail set -euo pipefail # Start a server yarn serve & SERVER_PID=$! # Run some cURL requests against the server ... # Stop the server kill $SERVER_PID ,即使其中一个服务器命令失败也是如此。有没有办法在Bash中实现这一目标?

2 个答案:

答案 0 :(得分:4)

#!/usr/bin/env bash

# Stop the script if any commands fail
set -euo pipefail

# Start a server
yarn serve &
SERVER_PID=$!

trap "kill $SERVER_PID" 0 1 2 3 15

# Run some cURL requests against the server
...

请注意使用trap

答案 1 :(得分:2)

插入

trap "kill $SERVER_PID" ERR

SERVER_PID=$!之后的新行中。

来自help trap

  

ERR表示每次命令失败都会导致执行ARG       启用-e选项时要退出的shell。