🔥

trapを含むBash scriptのstatus codeは難しい

に公開

TL;DR

trap付きスクリプトのstatus codeは、本文最後のコマンドの返り値になるが、trapの中でexitするとその値になる。
さらにtrapの中でexitしても無限ループにはならない。

実験

trap1.bash
#!/bin/bash

cleanup() {
    echo "Call cleanup"
}
trap cleanup EXIT

exit 117
trap2.bash
#!/bin/bash

cleanup() {
    echo "Call cleanup"
    exit 12
}
trap cleanup EXIT

exit 117
$ ./trap1.bash 
Call cleanup
$ echo $?
117
$ ./trap2.bash 
Call cleanup
$ echo $?
12

Discussion