Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

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

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 directory part the following way:

Currently I have:

pajton@dragon:~/workspace/projects/project1/folder1/test$

and would like to have:

pajton@dragon:~/workspace/.../folder1/test$

The truncating would occur if len($PWD) passes given threshold. I want to always keep the first path component and at least one last path component. Then as space permits, add more components taking from the right.

This is what I have currently. It works, but: 1) doesn't keep first path component, 2) doesn't respect cutting path at boundaries:

pwd_length=14
pwd_symbol="..."
newPWD="${PWD/#$HOME/~}"

if [ $(echo -n $newPWD | wc -c | tr -d " ") -gt $pwd_length ]
then
   newPWD="...$(echo -n $PWD | sed -e "s/.*(.{$pwd_length})/1/")"
else
   newPWD="$(echo -n $PWD)"
fi

And the result:

pajton@dragon:...sth/folder1/sample$ 

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...