且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何缩短命令行提示符的当前目录?

更新时间:2023-01-27 15:13:51

针对您的情况,使用awk而不是sed来考虑以下脚本:

Consider this script using awk instead of sed for your case:

pwd_length=14
pwd_symbol="..."
newPWD="${PWD/#$HOME/~}"
if [ $(echo -n $newPWD | wc -c | tr -d " ") -gt $pwd_length ]
then
   newPWD=$(echo -n $newPWD | awk -F '/' '{
   print $1 "/" $2 "/.../" $(NF-1) "/" $(NF)}')
fi
PS1='${newPWD}$ '

对于目录~/workspace/projects/project1/folder1/test的示例,它将PS1设置为:~/workspace/.../folder1/test

For your example of directory ~/workspace/projects/project1/folder1/test it makes PS1 as: ~/workspace/.../folder1/test

以上解决方案将设置您的提示,但正如您在注释中指出的那样,当您更改目录时,它不会动态更改PS1.因此,这里是可以在更改目录时动态设置PS1的解决方案.

Above solution will set your prompt but as you noted in your comment that it will NOT change PS1 dynamically when you change directory. So here is the solution that will dynamically set PS1 when you change directories around.

将这两行放在.bashrc文件中:

Put these 2 lines in your .bashrc file:

export MYPS='$(echo -n "${PWD/#$HOME/~}" | awk -F "/" '"'"'{
if (length($0) > 14) { if (NF>4) print $1 "/" $2 "/.../" $(NF-1) "/" $NF;
else if (NF>3) print $1 "/" $2 "/.../" $NF;
else print $1 "/.../" $NF; }
else print $0;}'"'"')'
PS1='$(eval "echo ${MYPS}")$ '

只有当当前目录的深度超过3个目录并且$PWD的长度大于14个字符时,awk中的

if (NF > 4 && length($0) > 14)条件才会应用特殊处理,否则PS1将保持为$PWD.

if (NF > 4 && length($0) > 14) condition in awk will only apply special handling when your current directory is more than 3 directories deep AND if length of $PWD is more than 14 characters otherwise and it will keep PS1 as $PWD.

例如:如果当前目录是~/workspace/projects/project1$,则PS1将是~/workspace/projects/project1$

eg: if current directory is ~/workspace/projects/project1$ then PS1 will be ~/workspace/projects/project1$

.bashrc中的上述效果在您的PS1上如下所示:

Effect of above in .bashrc will be as follows on your PS1:

~$ cd ~/workspace/projects/project1/folder1/test
~/workspace/.../folder1/test$ cd ..
~/workspace/.../project1/folder1$ cd ..
~/workspace/.../project1$ cd ..
~/.../projects$ cd ..
~/workspace$ cd ..
~$

注意更改目录时提示的更改方式.让我知道这是否不是您想要的.

Notice how prompt is changing when I change directories. Let me know if this is not what you wanted.