我正在用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中实现这一目标?
答案 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。