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

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

    Another approach, still using sed and awk to generate the prompt. This will convert your $HOME directory into ~, show you your root directory, your lowest level (current directory), and its parent, separated by .. for each directory in between.

    Inside of your .bashrc (or .bash_profile on OS X):

    function generate_pwd {
      pwd | sed s.$HOME.~.g | awk -F"/" '
      BEGIN { ORS="/" }
      END {
      for (i=1; i<= NF; i++) {
          if ((i == 1 && $1 != "") || i == NF-1 || i == NF) {
            print $i
          }
          else if (i == 1 && $1 == "") {
            print "/"$2
            i++
          }
          else {
            print ".."
          }
        }
      }'
    }
    export PS1="\$(generate_pwd) -> "
    

    The script uses awk's built in NF variable (number of fields) and positional variables ($1, $2 ...) to print each field (directory name) separated by the ORS variable (output record separator). It collapses the inner directories into .. in your prompt.

    Example of it in use:

    ~/ -> cd Documents/
    ~/Documents/ -> cd scripts/
    ~/Documents/scripts/ -> cd test1/
    ~/../scripts/test1/ -> cd test2
    ~/../../test1/test2/ -> pwd
    /Users/Brandon/Documents/scripts/test1/test2
    ~/../../test1/test2/ -> cd test3/
    ~/../../../test2/test3/ -> cd test4/
    ~/../../../../test3/test4/ -> pwd
    /Users/Brandon/Documents/scripts/test1/test2/test3/test4
    ~/../../../../test3/test4/ -> cd /usr/
    /usr/ -> cd local/
    /usr/local/ -> cd etc/
    /usr/local/etc/ -> cd openssl/
    /usr/../etc/openssl/ -> cd private/
    /usr/../../openssl/private/ ->
    

提交回复
热议问题