code-8
code-8

Reputation: 58790

How can I check for the current path in bash?

I'm working

on multiple projects : A, B, C, D, E and F. I go though all my projects via Terminal, and swapping between them via Terminal Tabs.

Sometimes, I confuse between projects because they have the same text color, in this case is yellow.

enter image description here


I'm trying

to achieve something like this:

enter image description here

I would like to assign a different color base on the current path of the project.

How to do I check for current path in bash ?


.bash_profile

#================================
#            Colors             =
#================================

black="\[\033[0;30m\]"
blue="\[\033[1;37m\]"
green="\[\033[0;32m\]"
cyan="\[\033[0;36m\]"
red="\[\033[0;31m\]"
purple="\[\033[0;35m\]"
brown="\[\033[0;33m\]"
lightgray="\[\033[0;37m\]"
darkgray="\[\033[1;30m\]"
lightblue="\[\033[1;34m\]"
lightgreen="\[\033[1;32m\]"
lightcyan="\[\033[1;36m\]"
lightred="\[\033[1;31m\]"
lightpurple="\[\033[1;35m\]"
yellow="\[\033[1;33m\]"
white="\[\033[1;37m\]"
nc="\[\033[0m\]"

if [ "\w" == "~/dev/projects/biv2" ]; then
  export PS1="──$white[$blue\w$white] \n└── $white"
fi

// Default Color
export PS1="──$white[$yellow\w$white] \n└── $white"

Upvotes: 1

Views: 769

Answers (1)

chepner
chepner

Reputation: 532208

You'll have to use PROMPT_COMMAND to check what the current directory is just before displaying the prompt, and set the value of PS1 accordingly.

prompt_cmd () {
    case $PWD in
        ~/dev/projects/biv2) dircolor=$yellow ;;
        ~/dev/projects/other) dircolor=$blue ;;
        # and so on. For any other directory,
        *) dircolor=$green
    esac
    PS1="──$white[$dircolor\w$white] \n└── $white"
}

PROMPT_COMMAND=prompt_cmd

Without PROMPT_COMMAND, you could do something like

set_dir_color () {
    case $PWD in
        ~/dev/projects/biv2) dircolor=$yellow ;;
        ~/dev/projects/other) dircolor=$blue ;;
        # and so on. For any other directory,
        *) dircolor=$green
    esac
    echo "$dircolor"
}

PS1="──$white[\$(set_dir_color)\w$white] \n└── $white"

Upvotes: 3

Related Questions