如何仅在 bash 中捕获 exit 1

Sim*_*ate 3 linux bash bash-trap

我有以下 bash 脚本:

#!/bin/bash


function hello {
    echo "Hello World!"
}

trap hello EXIT
Run Code Online (Sandbox Code Playgroud)

问题是该函数将在该脚本的任何退出代码上执行。如果我exit 1在脚本末尾附加 an ,Hello World!将会被打印,但它也会在 exit 0 上打印。

有没有办法在脚本中运行函数,但前提是脚本仅以退出代码 1 退出?(实际上除了 0 之外的任何值都可以。)

gle*_*man 5

捕获函数中的当前状态:

bye() {
  local status=$?
  (( status == 1 )) && echo "Hello World!"
  echo "Exiting with status $status"
  exit $status
}
trap bye EXIT
# ...
exit $some_status
Run Code Online (Sandbox Code Playgroud)