How can I shortern my command line prompt's current directory?

前端 未结 10 1840
野趣味
野趣味 2020-11-29 17:08

I am using Ubuntu and I am tired of this long prompts in bash when I am working with some deep directory hierarchy. So, I would like to tweak my PS1 to shorten the working d

10条回答
  •  执笔经年
    2020-11-29 17:22

    For people looking for a much simpler solution and don't need the name of the first directory in the path, Bash has built-in support for this using the PROMPT_DIRTRIM variable. From the documentation:

    PROMPT_DIRTRIM

    If set to a number greater than zero, the value is used as the number of trailing directory components to retain when expanding the \w and \W prompt string escapes (see Printing a Prompt). Characters removed are replaced with an ellipsis.

    For example:

    ~$ mkdir -p a/b/c/d/e/f
    ~$ cd a/b/c/d/e/f
    ~/a/b/c/d/e/f$ export PROMPT_DIRTRIM=2
    ~/.../e/f$ PROMPT_DIRTRIM=3
    ~/.../d/e/f$ 
    

    Downside: It depends on the directory level, not the length of the path, which you might not want.

    Upside: It's very simple. Just add export PROMPT_DIRTRIM=2 to your .bashrc.

提交回复
热议问题