代码之家  ›  专栏  ›  技术社区  ›  LandonSchropp

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

  •  1
  • LandonSchropp  · 技术社区  · 8 年前

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

    #!/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
    

    我想做的是确保 kill $SERVER_PID 始终在脚本末尾调用,即使其中一个服务器命令失败。有没有办法在Bash中实现这一点?

    2 回复  |  直到 8 年前
        1
  •  6
  •   Gilles Quénot ticktalk    8 年前
    #!/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

        2
  •  4
  •   Cyrus    8 年前

    插入

    trap "kill $SERVER_PID" ERR
    

    在之后的新行中 SERVER_PID=$! .

    从…起 help trap :

    ERR意味着每次命令失败都会导致 启用-e选项时退出shell。

    推荐文章