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

前端 未结 10 1942
野趣味
野趣味 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:38

    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}$ '
    

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

    UPDATE

    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.

    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}")$ '
    

    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.

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

    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.

提交回复
热议问题