Get current directory (without full path) in Fish Shell

My buddy finally made me start using Fish Shell, and I'm trying to set it up just like I had Bash. In PS1 PS1Set my current directory followed >. This, however, was not an absolute path (for example, /Users/me/Documents/...or ~/Documents/...). If I were in /Users/me/Documents/projects/Go/project1/, a hint would just say project1 >.

Is there an alternative "Shell" to replace \Wfor Bash? Again, I just need the folder I'm in, not the full path. I know that you can use echo (pwd)for all this.

I looked through the program basenameand echo "${PWD##*/}", but they only work in Bash.

+4
source share
3 answers

Taken from @Jubobs answer: basename- it's just a Unix utility; it is not associated with a particular shell and should work equally well in Bash and Fish.

It turned out that I used basenamein the wrong context and without a suffix.

This was resolved using the following:

function fish_prompt
    echo (basename $PWD) "><> "
end
+8
source

Alternative: fish ships with a function called prompt_pwdthat displays /Users/me/Documents/projects/Go/project1/as~/D/p/G/project1

function fish_prompt
    echo (prompt_pwd) "><> "
end
+1
source

Below is the full code prompt_pwd.fish. You must put it in a directory~/.config/fish/functions/

function prompt_pwd --description "Print the current working directory, shortened to fit the prompt"
    set -q argv[1]
    and switch $argv[1]
        case -h --help
            __fish_print_help prompt_pwd
            return 0
    end

    # This allows overriding fish_prompt_pwd_dir_length from the outside (global or universal) without leaking it
    set -q fish_prompt_pwd_dir_length
    or set -l fish_prompt_pwd_dir_length 1

    # Replace $HOME with "~"
    set realhome ~

    # @EDITED by Thiago Andrade
    set tmpdir (basename $PWD)
    set -l tmp (string replace -r '^'"$realhome"'($|/)' '~$1' $tmpdir)
    # ORIGINAL VERSION
    # set -l tmp (string replace -r '^'"$realhome"'($|/)' '~$1' $PWD)

    if [ $fish_prompt_pwd_dir_length -eq 0 ]
        echo $tmp
    else
        # Shorten to at most $fish_prompt_pwd_dir_length characters per directory
        string replace -ar '(\.?[^/]{'"$fish_prompt_pwd_dir_length"'})[^/]*/' '$1/' $tmp
    end
end

Then you will see something like this

enter image description here

+1
source

All Articles