在 Bash 退出之前运行脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5033354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run script before Bash exits
提问by Facundo Casco
I'd like to run a script every time I close a Bash session.
我想每次关闭 Bash 会话时都运行一个脚本。
I use XFCE and Terminal 0.4.5 (Xfce Terminal Emulator), I would like to run a script every time I close a tab in Terminal including the last one (when I close Terminal).
我使用 XFCE 和终端 0.4.5(Xfce 终端模拟器),我想每次关闭终端中的一个选项卡时都运行一个脚本,包括最后一个(当我关闭终端时)。
Something like .bashrc but running at the end of every session.
类似于 .bashrc 但在每个会话结束时运行的东西。
.bash_logout doesn't work
.bash_logout 不起作用
回答by DVK
You use trap(see man bash):
您使用trap(参见man bash):
trap /u1/myuser/on_exit_script.sh EXIT
The command can be added to your .profile/.login
该命令可以添加到您的 .profile/.login
This works whether you exit the shell normally (e.g. via exitcommand) or simply kill the terminal window/tab, since the shell gets the EXITsignal either way - I just tested by exiting my putty window.
无论您是正常退出外壳程序(例如通过exit命令)还是简单地终止终端窗口/选项卡,这都有效,因为外壳程序以EXIT任何方式获取信号 - 我只是通过退出我的腻子窗口进行了测试。
回答by Arturo Herrero
My answer is similar to DVK's answerbut you have to use a command or function, not a file.
我的回答类似于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.
So, you can add to your .bashrcsomething like the following code:
因此,您可以添加.bashrc类似以下代码的内容:
finish() {
# Your code here
}
trap finish EXIT
回答by jellyfish
Write you script in "~/.bash_logout". It executed by bash(1) when login shell exits.
在“~/.bash_logout”中编写脚本。它在登录 shell 退出时由 bash(1) 执行。
回答by gailbear
If you close your session with "exit", might be able to something like
alias endbash="./runscript;exit"and just exit by entering endbash. I'm not entirely sure this works, as I'm running windows at the moment.
如果你用“exit”关闭你的会话,也许可以
alias endbash="./runscript;exit"通过输入 endbash 来退出。我不完全确定这是否有效,因为我目前正在运行 Windows。
edit: DVK has a better answer.
编辑:DVK 有更好的答案。

