6

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!

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
Vender Aeloth
  • 690
  • 1
  • 12
  • 27

2 Answers2

17

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
Sriharsha Kalluru
  • 1,743
  • 3
  • 21
  • 27
7

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.
mouviciel
  • 66,855
  • 13
  • 106
  • 140