2

Is it possible to have the name of the current working directory in the prompt in shell ?

Im working on OSX and CentOS in multiple projects under /srv/... and a mistake for wrong directory is quickly made.

I would like to have

[current_path] in my prompt somehow , perhaps coloured Is this possible?

For example like /srv/myproject it would give prompt [root@server [myproject]# This should stay the same even in /srv/myproject/app/etc

Rubytastic
  • 223
  • 1
  • 2
  • 14

3 Answers3

2

The character sequence for the full current working directory in $PS1 is \w. See "Tip: Prompt magic" for more details.

Ignacio Vazquez-Abrams
  • 45,019
  • 5
  • 78
  • 84
2

I use the following string in /etc/bashrc on my Linux systems. Usually it's a matter of replacing an upper-case "W" with lower-case "w" on most default Bash installations:

PS1="[\u@\h \w]\\$ "

This yields:

[root@MDMarra /ppro/edi/0010/GOODBI/receive/archive]#  

instead of:

[root@MDMarra archive]#
ewwhite
  • 194,921
  • 91
  • 434
  • 799
0

This should be close to what you're looking for:

PS1="\$([[ \$PWD == /srv/*/* ]] && p=\${PWD#/*/} && p=[\${p%%/*}]; echo -n \"\$p$ \" )"

For testing, use this to show the full directory along with the truncated one for comparison:

PS1="\$([[ \$PWD == /srv/*/* ]] && p=\${PWD#/*/} && p=[\${p%%/*}]; echo -n \"[\$PWD] \$p$ \" )"

The escapes cause the variable expansion to be deferred until the prompt is issued. The parameter expansions strip off the first level directory and all directory levels below the second level.

You will probably need:

shopt -s promptvars

but I think it's the default.

The prompt only does its job when you're in a directory under /srv

This is one way to add some color. It makes the project name cyan.

PS1="\$([[ \$PWD == /srv/*/* ]] && p=\${PWD#/*/} && p='[\[\033[1;36m\]'\${p%%/*}'\[\033[0m\]]'; echo -n \"\$p$ \" )"
Dennis Williamson
  • 60,515
  • 14
  • 113
  • 148