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

问题描述 投票:0回答:1

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

/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

怎么实现呢?

附:路径可以包含空格。

bash directory prompt ps1
1个回答
0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.