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

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

    Not so different from previous solutions. However, maybe a bit more readable/editable. However, no solution to the folder name boundary, only focusing on the length of the prompt.

    ### SET MY PROMPT ###
    if [ -n "$PS1" ]; then
        # A temporary variable to contain our prompt command
        NEW_PROMPT_COMMAND='
            pwd_short=${PWD/#$HOME/\~};
            if [ ${#pwd_short} -gt 53 ]; then
                TRIMMED_PWD=${pwd_short: 0: 25}...${pwd_short: -25}
            else
                TRIMMED_PWD=${pwd_short}
            fi
        '
    
        # If there's an existing prompt command, let's not 
        # clobber it
        if [ -n "$PROMPT_COMMAND" ]; then
            PROMPT_COMMAND="$PROMPT_COMMAND;$NEW_PROMPT_COMMAND"
        else
            PROMPT_COMMAND="$NEW_PROMPT_COMMAND"
        fi
    
        # We're done with our temporary variable
        unset NEW_PROMPT_COMMAND
    
        # Set PS1 with our new variable
        # \h - hostname, \u - username
        PS1='\u@\h: $TRIMMED_PWD\$ '
    fi
    

    added to the .bashrc file. All parts of the prompt is updated properly. The first part is shortened if you're in your home directory. Example:

    user@computer: ~/misc/projs/solardrivers...src/com/mycompany/handles$

提交回复
热议问题