如何在每次退出 zsh shell(包括非登录 shell)时运行命令

如何在每次退出 zsh shell(包括非登录 shell)时运行命令

每次退出 shell 时,我一直尝试运行命令来清理一些临时文件。

我最初认为这将是我的工作,.zlogout但如果我在终端模拟器(小猫)中打开多个 shell,它似乎不会被执行。根据我在文档中找到的内容,仅.zlogin适用.zlogout于登录 shell,如果我错了,请纠正我,当您只是在终端模拟器中打开不同的选项卡或窗口时,情况并非如此。

非登录 shell的等效项是什么.zlogout?或者在非登录 shell 中实现类似效果的推荐方法是什么?

答案1

添加一个函数,例如

function shellExit {
  # Your commands
}

以及一个陷阱,例如

trap shellExit EXIT

.zshrc

答案2

这里面有一个例子zsh 指南~/.zlogout使用以下命令的非登录 shell 的来源TRAPEXIT功能。这似乎正是您想要的。

TRAPEXIT() {
    # commands to run here, e.g. if you 
    # always want to run .zlogout:
    if [[ ! -o login ]]; then
      # don't do this in a login shell
      # because it happens anyway
      . ~/.zlogout
    fi
  }

将此功能添加到您的~/.zshrc.

相关内容