0

Consider fixed absolute path to some directory with arbitrary subdirectories:

/full/path/to/fixed/directory
/full/path/to/fixed/directory/first_subdirectory
/full/path/to/fixed/directory/first_subdirectory/second_subdirectory

and arbitrary other directory that is not subdirectory of foregoing directory: /other/path

I want see the following in the terminal:

user@host: .../directory$ 
user@host: .../directory/first_subdirectory
user@host: .../directory/first_subdirectory/second_subdirectory
user@host: /other/path$ 

where the last line is a typical case but other lines are instead of

user@host: /full/path/to/fixed/directory$ 
user@host: /full/path/to/fixed/directory/first_subdirectory
user@host: /full/path/to/fixed/directory/first_subdirectory/second_subdirectory

How to implement it?

P.S. Paths can contain whitespaces.

1 Answers1

0

I'd use the special PROMPT_COMMAND var. For example:

[the-old-prompt] $ cat ps1
g_theSpecialDir=/tmp/im/the/magic/directory
g_pwd=

_prompt_cmd()
{
    if [[ $PWD/ == $g_theSpecialDir/* ]]; then
        g_pwd=.../${g_theSpecialDir##*/}${PWD#$g_theSpecialDir}
    else
        g_pwd=$PWD
    fi
}

PROMPT_COMMAND=_prompt_cmd
PS1='[\u@\h $g_pwd] $ '
[the-old-prompt] $ source ./ps1
[whjm@localhost /tmp] $ cd /tmp/im/the/magic/directory/
[whjm@localhost .../directory] $ cd dir1/
[whjm@localhost .../directory/dir1] $ cd dir2/
[whjm@localhost .../directory/dir1/dir2] $ cd /tmp/
[whjm@localhost /tmp] $

You can find the PROMPT_COMMAND var in the Bash manual. And this solution enables you to include anything you like in the prompt.

pynexj
  • 15,152
  • 5
  • 24
  • 45
  • Thanks. I changed the function a little bit, and now it works for paths with whitespaces and show '~'' instead of home directory: _prompt_cmd() { if [[ "${PWD}/" == "${g_theSpecialDir}/"* ]]; then g_pwd=.../${g_theSpecialDir##*/}${PWD#"${g_theSpecialDir}"} elif [[ "${PWD}/" == "${HOME}/"* ]]; then g_pwd=~${PWD#"$HOME"} else g_pwd=${PWD} fi } –  Mar 01 '15 at 16:37