Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic change bash prompt according to path

I would like to know if it is possible to change the PS1 according to the current path or pwd value?

For example:

cd /home/user/directory1
PS1=[\e[1;32m\u\e[m@\e[1;34m\h\e[m \e[1;33m\W\e[m]

But if i'm in an another directory :

cd /home/user/thisdirectory
PS1=[\w]

Thank you in advance!

like image 835
Vender Aeloth Avatar asked Nov 04 '14 09:11

Vender Aeloth


2 Answers

You can use this code.

[user1@myhost ~]myfunc() { DIR=`pwd`;if [ "$DIR" = "/home/user1" ]; then  export PS1="[\e[1;32m\u\e[m@\e[1;34m\h\e[m \e[1;33m\W\e[m]" ;else export PS1="[\w]";fi; }
[user1@myhost ~]PROMPT_COMMAND="myfunc"
[user1@myhost ~]cd /tmp
[/tmp]cd
[user1@myhost ~]cd /etc
[/etc]cd
[user1@myhost ~]

When I am changing the directory the prompt is getting changed.

like image 157
Sriharsha Kalluru Avatar answered Nov 03 '22 15:11

Sriharsha Kalluru


The PROMPT_COMMAND bash variable is what you're looking for:

PROMPT_COMMAND
       If set, the value is executed as a command prior to issuing
       each primary prompt.
like image 43
mouviciel Avatar answered Nov 03 '22 16:11

mouviciel