关闭终端时执行脚本

Vik*_*lov 5 command-line bash scripts

我想在关闭终端时执行特定的 sh 脚本。

我编辑了.bash-logout文件,在 if 语句中添加了这行代码

[ -x /home/user/Documents/logout_msg.sh ] && /home/user/Documents/logout_msg
Run Code Online (Sandbox Code Playgroud)

我制作了logout_msg.sh可执行文件,并且还在 if 语句之外添加了带有 sleep 命令的基本回显消息,但是在关闭终端时没有显示。

可能是什么问题?

ter*_*don 5

~/.bash_logout文件仅在您退出登录 shell(来自)时才获取man bash

当交互式登录 shell 退出,或非交互式登录 shell 执行 exit 内置命令时,bash 从文件 ~/.bash_logout(如果存在)读取并执行命令。

当您打开终端时,您正在运行一个交互式非登录 shell,因此~/.bash_logout无关紧要。有关不同类型 shell 的更多信息,请参阅我的回答

为了在每次关闭终端时都执行某些操作,您可以使用trap设置命令在每次交互式 bash 会话退出时运行。为此,请将此行添加到您的~/.bashrc

trap /home/user/Documents/logout_msg.sh EXIT 
Run Code Online (Sandbox Code Playgroud)

当然,如果该脚本正在向终端打印一条消息,您需要确保logout_msg.sh包含一个sleep命令,以便用户有时间阅读该消息。就像是:

echo "Whatever message you want"
sleep 10 ## wait for 10 seconds
Run Code Online (Sandbox Code Playgroud)