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

时间:2015-03-01 04:49:18

标签: bash directory prompt ps1

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

/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。路径可以包含空格。

1 个答案:

答案 0 :(得分: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] $

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