trap
不是传播到子shell,但是有些方法允许子shell报告父shell的陷阱,而另一些则不。我用bash在macOS上做了一些测试。
GNU bash版本4.4.12(1)-发行版(x86_64-apple-darwin16.3.0):
trap 'echo hello' EXIT
trap # trap -- 'echo hello' EXIT
echo "$(trap)" # trap -- 'echo hello' EXIT
trap | cat # trap -- 'echo hello' EXIT
(trap) | cat # trap -- 'echo hello' EXIT
cat < <(trap) # empty
cat <<< "$(trap)" # empty
bash -c 'trap' # empty
trap & # trap -- 'echo hello' EXIT
GNU bash版本3.2.57(1)-发行版(x86_64-apple-darwin16):
trap 'echo hello' EXIT
trap # trap -- 'echo hello' EXIT
echo "$(trap)" # trap -- 'echo hello' EXIT
trap > >(cat) # trap -- 'echo hello' EXIT
trap | cat # empty
(trap) | cat # empty
cat < <(trap) # empty
cat <<< "$(trap)" # empty
bash -c 'trap' # empty
trap & # empty
很高兴知道这trap_output="$(trap)"
将捕获陷阱输出。如果无法trap >trap_output_file
将其输出到文件(fifo无法在中工作bash 3.2.57
)然后再读回,那么我想不出其他任何方法来做到这一点trap_output="$(<trap_output_file)"
fifo将无法使用,bash 3.2.57
因为它trap &
为空bash 3.2.57
但不是bash 4.4.12
GNU bash版本4.4.12(1)-发行版(x86_64-apple-darwin16.3.0):
mkfifo /tmp/fifo; trap >/tmp/fifo & trap_output=$(</tmp/fifo); rm -f /tmp/fifo; echo "$trap_output"
# trap -- 'echo hello' EXIT
mkfifo /tmp/fifo; trap_output=$(</tmp/fifo) & trap >/tmp/fifo; rm -f /tmp/fifo; echo "$trap_output"
# empty because trap_output=$(</tmp/fifo) sets the variable in a subshell
GNU bash版本3.2.57(1)-发行版(x86_64-apple-darwin16):
mkfifo /tmp/fifo; trap >/tmp/fifo & trap_output=$(</tmp/fifo); rm -f /tmp/fifo; echo "$trap_output"
# empty because trap >/tmp/fifo & is empty since it uses trap &
mkfifo /tmp/fifo; trap_output=$(</tmp/fifo) & trap >/tmp/fifo; rm -f /tmp/fifo; echo "$trap_output"
# empty because trap_output=$(</tmp/fifo) sets the variable in a subshell