Bash 退出前运行脚本

发布于 2024-10-17 19:26:58 字数 177 浏览 2 评论 0原文

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

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

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

.bash_logout 不起作用

I'd like to run a script every time I close a Bash session.

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).

Something like .bashrc but running at the end of every session.

.bash_logout doesn't work

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

知你几分 2024-10-24 19:26:58

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

trap /u1/myuser/on_exit_script.sh EXIT

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

无论您正常退出shell,这都有效(例如通过 exit 命令)或者干脆终止终端窗口/选项卡,因为 shell 会以任何方式获取 EXIT 信号 - 我只是通过退出 Putty 窗口进行测试。

You use trap (see man bash):

trap /u1/myuser/on_exit_script.sh EXIT

The command can be added to your .profile/.login

This works whether you exit the shell normally (e.g. via exit command) or simply kill the terminal window/tab, since the shell gets the EXIT signal either way - I just tested by exiting my putty window.

小伙你站住 2024-10-24 19:26:58

我的答案类似于 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

My answer is similar to DVK's answer but you have to use a command or function, not a file.

$ 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 .bashrc something like the following code:

finish() {
  # Your code here
}

trap finish EXIT
陌上芳菲 2024-10-24 19:26:58

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

Write you script in "~/.bash_logout". It executed by bash(1) when login shell exits.

远山浅 2024-10-24 19:26:58

如果您使用“退出”关闭会话,也许可以执行类似的操作
alias endbash="./runscript;exit" 并输入 endbash 退出。我不完全确定这是否有效,因为我现在正在运行 Windows。

编辑:DVK 有更好的答案。

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.

edit: DVK has a better answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文