s5s s5s - 3 months ago 20x
Linux Question

Linux shell (bash/zsh) - change background color when under specific directory

I would like to change the background color of a shell (zsh but bash will do as well) everytime I go under a specific directory. For example, I would like to change the background color every time I am in /mnt/data to say red and change it back to normal if I go out of /mnt/data/...

To change the background and preserve my current prompt, I do:

export PS1="$PS1 %{$'\e[0;41m'%}"

I am not sure how to hook this up so that it is evaluated (wrapped in an if-statement) every time I change working directory.


The trick is to use the command substitution in PS1. The following kind of works for me in bash:

PS1='$(if [[ $PWD == /mnt/data* ]] ; then printf "\[\e[0;41m\]" ; else printf "\[\e[m\]" ; fi) %'

By "kind of" I mean the fact that the behaviour on the command line immediately after changing to/from the directory is a bit weird (e.g. the background changes after you press Backspace).

You can also use the PROMPT_COMMAND variable which is more suitable for code than the prompt itself:

PROMPT_COMMAND='if [[ $PWD == /mnt/data* ]] ; then printf "\e[0;41m" ; else printf "\e[m" ; fi'

It's cleaner to keep the code in a function with all the proper indentation, and just call the function from the variable:

colour_mnt_data () {
    if [[ $PWD == /mnt/data* ]] ; then
        printf '\e[0;41m'
        printf '\e[m'