【发布时间】:2011-02-17 19:04:07
【问题描述】:
我想在每次关闭 Bash 会话时运行一个脚本。
我使用 XFCE 和 Terminal 0.4.5(Xfce Terminal Emulator),我想在每次关闭终端中的一个选项卡(包括最后一个选项卡)时运行一个脚本(当我关闭终端时)。
类似于 .bashrc 但在每个会话结束时运行。
.bash_logout 不起作用
【问题讨论】:
我想在每次关闭 Bash 会话时运行一个脚本。
我使用 XFCE 和 Terminal 0.4.5(Xfce Terminal Emulator),我想在每次关闭终端中的一个选项卡(包括最后一个选项卡)时运行一个脚本(当我关闭终端时)。
类似于 .bashrc 但在每个会话结束时运行。
.bash_logout 不起作用
【问题讨论】:
你使用trap(见man bash):
trap /u1/myuser/on_exit_script.sh EXIT
该命令可以添加到你的.profile/.login
无论您是正常退出 shell(例如,通过exit 命令)还是简单地终止终端窗口/选项卡,这都有效,因为无论哪种方式,shell 都会收到EXIT 信号 - 我刚刚通过退出我的腻子窗口进行了测试。
【讨论】:
我的回答类似于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
【讨论】:
在“~/.bash_logout”中编写脚本。它在登录 shell 退出时由 bash(1) 执行。
【讨论】:
如果你用“exit”关闭你的会话,可能会像这样
alias endbash="./runscript;exit" 然后输入 endbash 退出。我不完全确定这是否有效,因为我目前正在运行 Windows。
编辑:DVK 有更好的答案。
【讨论】: