2

I want to execute some commands every time I exit from bash, but cannot find a way to do it. There is a ~/.bash_logout file for when you are logging out, but normally we use interactive shell instead of login shell, so this is not very useful for this purpose.

Is there a way to do this? Thanks!

4

1 回答 1

5

您可以捕获 EXIT 信号。

exit_handler () {
  # code to run on exit
}

trap 'exit_handler' EXIT

从技术上讲,trap exit_handler EXIT也可以。我引用它是为了强调 to 的第一个参数trap是一个本质上传递给 的字符串,eval而不一定是单个函数名。你可以很容易地写

trap 'do_this; do_that; if [[ $PICKY == yes ]]; then one_more_thing; fi' EXIT

而不是将您的代码收集到一个函数中。

于 2013-04-25T13:57:33.423 回答