7

In tcsh, I have the default:

prompt  [%m:%c3] %n%# 

which gives prompts like:

[woehler:hacking/c/hello] ajcarr% 

and

[woehler:~] ajcarr% 

In other words, the current directory and up to the next two above it in the path.

In ksh93 or bash, the substitution of $HOME by ~ is easy, as is extracting the name of just the current directory, but I have yet to find a way of replicating the %c3 behaviour of tcsh. At present in ksh93 I have:

[ajcarr@Woehler] hello $ 

and

[ajcarr@Woehler] ~ $ 

Does anyone have any suggestions about how to do this?

8

In ksh93:

PS1='${PWD#${PWD%?/*/*/*}?/} \$ '
share/doc/libnl-3-dev $ _

PS1='[${HOSTNAME%%.*}:${PWD#${PWD%?/*/*/*}?/}] $USER% '
[host:share/doc/libnl-3-dev] user% _

If you want it to also replace $HOME with ~, something nastier is needed:

PS1='$(d=${PWD/#$HOME/"~"};printf %s "${d#${d%?/*/*/*}?/}") $ '
~/w/maemo $ cd sb2-pathmaps
w/maemo/sb2-pathmaps $ _

PS1='$(d=${PWD/#$HOME/"~"};printf %s "[${HOSTNAME%%.*}:${d#${d%?/*/*/*}?/}]") $USER% '
[host:w/maemo/sb2-pathmaps] user% _

All this should also work in bash, though bash has its own prompt escapes (eg. \h for ${HOSTNAME%%.*}) and path shortening mechanism (with PROMPT_DIRTRIM).

Also, the nastier variant will be really nasty, because bash, unlike ksh93, will fork() a separate process for each $(...; printf ...) command substitution, even if it contains only builtins. This also holds true for pdksh derived shells, like mksh.


zsh has prompt escapes quite similar but not identical to tcsh:

zsh$ PS1='[%m:%3c] %n%# '
[host:share/doc/libnl-3-dev] user% _

Note:

The $HOSTNAME variable is not set by default in ksh93; instead of it you could use the uname builtin (after enabling it with PATH=/opt/ast/bin:$PATH; the /opt/ast/bin path doesn't need to exist):

PS1='$(d=${PWD/#$HOME/"~"};h=$(uname -n); printf %s "[${h%%.*}:${d#${d%?/*/*/*}?/}]") $USER% '

Unlike the \h escape in bash or %m escape in zsh or tcsh this will track the hostname changes.

6

For bash, you could achieve similar results by setting the PROMPT_DIRTRIM variable:

$ PS1='[\u@\h] \w\$ '
[schaller@r2d2] ~$ pwd
/home/schaller
[schaller@r2d2] ~$ PROMPT_DIRTRIM=3
[schaller@r2d2] ~$ cd /home/schaller/tmp/513924/another/directory/here
[schaller@r2d2] ~/.../another/directory/here$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.