Skip to content

Instantly share code, notes, and snippets.

@davidmh
Last active November 28, 2020 13:37
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidmh/721241c7c34f841eed07 to your computer and use it in GitHub Desktop.
Save davidmh/721241c7c34f841eed07 to your computer and use it in GitHub Desktop.
Showing git branch in fish shell prompt. Put following code at the end of ~/.config/fish/config.fish. It will also highlight in red if branch is dirty. Based on http://zogovic.com/post/37906589287/showing-git-branch-in-fish-shell-prompt
set fish_git_dirty_color red
set fish_git_not_dirty_color green
function parse_git_branch
set -l branch (git branch 2> /dev/null | grep -e '\* ' | sed 's/^..\(.*\)/\1/')
set -l git_status (git status -s)
if test -n "$git_status"
echo (set_color $fish_git_dirty_color)$branch(set_color normal)
else
echo (set_color $fish_git_not_dirty_color)$branch(set_color normal)
end
end
function fish_prompt
set -l git_dir (git rev-parse --git-dir 2> /dev/null)
if test -n "$git_dir"
printf '%s@%s %s%s%s:%s> ' (whoami) (hostname|cut -d . -f 1) (set_color $fish_color_cwd) (prompt_pwd) (set_color normal) (parse_git_branch)
else
printf '%s@%s %s%s%s> ' (whoami) (hostname|cut -d . -f 1) (set_color $fish_color_cwd) (prompt_pwd) (set_color normal)
end
end
@SidOfc
Copy link

SidOfc commented Feb 18, 2018

Initially I had mine working more or less like this, using git branch command to fetch branch name.
Then, when creating some new project (and thus, an empty git repo with it), git branch failed to show that I was on any branch and the prompt did not show up.

I've found parsing git status to be more reliable since it also works on repo's without any commits.
To fix this for empty repo's, replace set -l branch ... line with set -l branch (git status | head -1 | string split ' ')[-1].

Given this git status for a repository with commits:

On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

And this one for a repository without commits:

On branch master

No commits yet

nothing to commit (create/copy files and use "git add" to track)

Both will correctly return the branch master.

Cheers for the git status -s switch, better than also parsing the last line of git status :) Too bad git branch fails to show a branch without commits present, too :(

@si-harps
Copy link

Thanks for this

@HarryHenryGebel
Copy link

HarryHenryGebel commented Nov 28, 2020

You can also just type fish_config on the command line, click on prompt and select a prompt with the current branch from the large number of prompts offered. I use lonetwin.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment