19

每次关闭 Bash 会话时,我都想运行一个脚本。

我使用 XFCE 和 Terminal 0.4.5(Xfce Terminal Emulator),每次我关闭终端中的一个选项卡(包括最后一个选项卡)时(当我关闭终端时),我都想运行一个脚本。

.bashrc 之类的东西,但在每个会话结束时运行。

.bash_logout 不起作用

4

4 回答 4

23

您使用trap(参见man bash):

trap /u1/myuser/on_exit_script.sh EXIT

该命令可以添加到您的.profile/.login

无论您是正常退出 shell(例如通过exit命令)还是简单地终止终端窗口/选项卡,这都有效,因为 shell 以EXIT任何一种方式获取信号 - 我刚刚通过退出我的 putty 窗口进行了测试。

于 2011-02-17T19:21:48.647 回答
9

我的回答类似于DVK 的回答,但您必须使用命令或函数,而不是文件。

$ man bash

   [...]

   trap [-lp] [[arg] sigspec ...]
          The command arg is to be read and executed when the shell
          receives signal(s) sigspec.

          [...]

          If a sigspec is EXIT (0) the command arg is executed on
          exit from the shell.

因此,您可以添加.bashrc类似以下代码的内容:

finish() {
  # Your code here
}

trap finish EXIT
于 2016-03-25T16:41:55.467 回答
2

在“~/.bash_logout”中编写脚本。它在登录 shell 退出时由 bash(1) 执行。

于 2013-11-08T17:08:30.837 回答
0

如果你用“exit”关闭你的会话,也许可以 alias endbash="./runscript;exit"通过输入 endbash 来退出。我不完全确定这是否有效,因为我目前正在运行 Windows。

编辑:DVK 有一个更好的答案。

于 2011-02-17T19:15:25.870 回答