自定义 PS1:所有目录的常规 PS1,不包括带有子目录的单个目录

Custom PS1: usual PS1 for all directories excluding single directory with subdirectories

考虑到具有任意子目录的某个目录的固定绝对路径:

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

不是上述directory子目录的任意其他目录:/other/path

我想在终端中看到以下内容:

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

其中最后一行是典型案例,但其他行不是

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

如何实现?

P.S。路径可以包含空格。

我会使用特殊的 PROMPT_COMMAND 变量。例如:

[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] $

您可以在 Bash manual 中找到 PROMPT_COMMAND 变量。此解决方案使您能够在提示中包含任何您喜欢的内容。