Dynamically changing bash tooltip along the way

I would like to know if PS1 can be changed according to the current path or pwd value?

For instance:

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 am in a different directory:

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

Thank you in advance!

+4
source share
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 change the directory, the request changes.

+8
source

The PROMPT_COMMANDbash variable is what you are looking for:

PROMPT_COMMAND
       If set, the value is executed as a command prior to issuing
       each primary prompt.
+5
source

All Articles