在Bash退出之前运行脚本

时间:2011-02-17 19:04:07

标签: bash exit xfce

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

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

类似.bashrc,但在每个会话结束时运行。

.bash_logout不起作用

4 个答案:

答案 0 :(得分:16)

您使用trap(请参阅man bash):

trap /u1/myuser/on_exit_script.sh EXIT

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

无论你是否正常退出shell(例如通过exit命令)或者只是终止终端窗口/标签,这都有效,因为shell会以任意方式获取EXIT信号 - 我只是通过退出我的测试腻子窗口。

答案 1 :(得分:7)

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

$ 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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

如果您使用“退出”关闭会话,可能会有类似的结果 alias endbash="./runscript;exit"然后输入endbash退出。我不完全确定这是有效的,因为我现在正在运行窗户。

编辑:DVK有更好的答案。