Search code examples
linuxbashshellconsolezsh

Linux shell (Bash/Z shell) - change background color when under a specific directory


I would like to change the background color of a shell (Z shell, but Bash will do as well) every time 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.


Solution

  • 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 shell 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'
        else
            printf '\e[m'
        fi
    }
    PROMPT_COMMAND='colour_mnt_data'