在Bash退出之前运行脚本

Fac*_*sco 17 bash xfce exit

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

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

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

.bash_logout不起作用

DVK*_*DVK 17

你用trap(见man bash):

trap /u1/myuser/on_exit_script.sh EXIT
Run Code Online (Sandbox Code Playgroud)

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

无论你是正常退出shell(例如通过exit命令)还是简单地终止终端窗口/标签,这都有效,因为shell会以EXIT任何方式获取信号 - 我只是通过退出我的putty窗口进行测试.


Art*_*ero 7

我的答案类似于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.
Run Code Online (Sandbox Code Playgroud)

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

finish() {
  # Your code here
}

trap finish EXIT
Run Code Online (Sandbox Code Playgroud)