简体   繁体   English

当前工作目录更改的 Bash 事件处理程序

[英]Bash event handler for current working directory change

Is there a simple way in Bash to detect changing of current working directory? Bash 中是否有一种简单的方法来检测当前工作目录的更改? I want to change window title every time I navigate using cd command.每次使用cd命令导航时,我都想更改窗口标题。 I want to include the repository's directory name in the title of the console window.我想在控制台窗口的标题中包含存储库的目录名称。 If CWD is not a repository then the title can be empty.如果 CWD 不是存储库,则标题可以为空。

For example:例如:

cd Documents/Repositories    # after this line I want window title to be empty ''  
cd repository1               # after this line I want window title to be 'repository1'   
cd ..                        # after this line I want window title to be empty ''   
cd repository2               # after this line I want window title to be 'repository2'  

Is there a way to detect when CWD has changed (kind of like an event handler)?有没有办法检测 CWD 何时发生变化(有点像事件处理程序)?

What you could do is overwrite the cd function in ~/.profile and add more parsing to it:您可以做的是覆盖~/.profile的 cd 函数并为其添加更多解析:

PROMPT_COMMAND='echo -ne "\033]0;${MYDIR}\007"'
function cd {
    MYDIR="${1:-${HOME}}"
    builtin cd "${MYDIR}"
    # ADD PARSING HERE
}

But I would suggest not to do this, since you probably want to have a directory as title regardless whether you navigate to .. or not.但我建议不要这样做,因为无论您是否导航到.. ,您可能都希望将目录作为标题。 I suggest to display the last 30 characters of your current directory:我建议显示当前目录的最后 30 个字符:

PROMPT_COMMAND='echo -ne "\033]0;..${PWD: -30}\007"'

You can read about different shells here .您可以在此处阅读有关不同 shell 的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM