简体   繁体   中英

Bash event handler for current working directory change

Is there a simple way in Bash to detect changing of current working directory? I want to change window title every time I navigate using cd command. 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.

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

What you could do is overwrite the cd function in ~/.profile and add more parsing to it:

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:

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

You can read about different shells here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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