Outputting dirty state of git repo in command line issue - bash

if i run this in command line with in git repo
git status 2> /dev/null | grep -iw 'modified'
the output i get
# modified: .rvmrc
so my assumption is that if i plug this in into if statement i will get true that will execute the line of code
but when i created function as part of the .bash_profile, and here is the code i have:
## Prompt ##
path="$white\w$reset"
folder_name="$white\W$reset"
git_branch="\$(git branch 2>/dev/null | grep -e '\* ' | sed 's/^..\(.*\)/$red(\1)$reset/')"
rvm="$green(\$(~/.rvm/bin/rvm-prompt i v p))$reset"
# Checks if working tree is dirty
function _git_st {
if [[ $(git status 2> /dev/null | grep -iw 'modified') ]]; then
echo "[x]"
fi
}
git_st="$yellow`_git_st`$reset"
PS1="$rvm $folder_name $git_branch $git_st \$ "
X is not echoed.... i am bit lost, and not sure what i am doing wrong.
this is the out put i get:
(ruby-1.9.2-p290) folder-git (master) $ git status
# On branch master
# Changes not staged for commit:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: .rvmrc
#
no changes added to commit (use "git add" and/or "git commit -a")
(ruby-1.9.2-p290) folder-git (master) $

The reason for this is because you are using a variable git_st to set PS1 which will be evaluated at the time of setting PS1. What you can try is to invoke the function _git_st be called instead of using git_st i.e. try something on the lines of:
PS1="$rvm $folder_name $git_branch \$(_git_st) \$ ".
Also you might be interested to know that newer versions of git provide functions along with bash completion which provide such utilities. You can take a look at __git_ps1 function if it is available.
Hope this helps!
P.S.: Here is SO post which might provide some pointers for using __git_ps1. This is the quick search result from Google.

Related

Trying to make a pre-commit hook that checks if files in index are formatted correctly

I've been trying to make a pre-commit hook that checks if files in the index are formatted correctly. I've tried so many things already but I just can't get the grep to work correctly. This is my code right now:
for FILE in $(git diff --cached --name-only)
do
if [[ "$FILE" =~ \.(c|h|cpp|cc)$ ]]; then
exec C:/dev/uct/clang-format-15.0.3.exe --dry-run -Werror $FILE | grep -c "violations"
fi
done
I expect it to print the number of files that have formatting issues (I actually want to search for the string -Wclang-format-violations but I simplified it for testing).
If I &> the clang-format output to a file the violations correctly printed to that file.
exec C:/dev/uct/clang-format-15.0.3.exe --dry-run -Werror $FILE &> temp.txt
If I then run grep from the command line on that file it works.
grep -c violations temp.txt
I also tried grep on the file from the script but for some reason that didn't produce any output either (though I would prefer to not have to create a file).
exec C:/dev/uct/clang-format-15.0.3.exe --dry-run -Werror $FILE &> temp.txt
grep -c violations temp.txt
What am I doing wrong? I thought I would get this to work in half an hour at most.
The problem with grep is that you're not redirecting stderr, only stdout. (In your redirection to a file, you are redirecting stderr as well, with >&.) To capture stderr in the pipe, use |&.
However you have a mismatch between what's staged to be committed and what you're looking at. In git, a file isn't staged to be committed, but its contents are. That means that you can stage - for example - part of a files contents to be committed. The file's contents in the working directory thus would not match what is staged.
Here's a concrete example:
echo "hello" > hello_world.txt
git add hello_world.txt
echo "world" >> hello_world.txt
At this point, the contents staged in the index (from the git add on line 2) are hello. But the file contains hello world on disk.
git status will show the file both as staged and modified:
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: hello_world.txt
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: hello_world.txt
If you were to run git commit now, only the hello would be committed, not the file as it exists on disk.
That means that you want to look at the staged contents of the file -- which is what will actually be committed -- not just the file on disk. Otherwise you may get false positives or negatives.
To handle this case, you can pass what's staged to clang-format using the git show command. (git show :filename will output the staged contents of filename.)
Try this:
for FILE in $(git diff --cached --name-only)
do
if [[ "$FILE" =~ \.(c|h|cpp|cc)$ ]]; then
git cat-file --filters ":${FILE}" | C:/dev/uct/clang-format-15.0.3.exe --dry-run -Werror --assume-filename="${FILE}" |& grep -c grep -c "\-Wclang\-format\-violations"
fi
done

change directory in bash is not affecting the post-commit hook

i've made the following bash script to commit the parent repo after some change in submodule.
it's all about that the script want to cd .. to check the parent repo current branch but the problem is that the cd .. is not affecting the upcoming commands because i guess the subshell
i've tried to run
1- cd ../ && before each command
2- make alias but didn't succeed
3- run exec but the script didn't continued
#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments. The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "post-commit".
commit_msg= git log -1 --pretty=%B
if [[ $(git branch | grep \* | cut -d ' ' -f2) == "int1177/next" ]]; then
cd ..
if [[ $(git branch | grep \* | cut -d ' ' -f2) == "B0/next" ]]; then
git add 6_Tests
git commit -m "bs esss"
echo "development branch B0/next has now new commit"
else
echo "development branch isn't B0/next"
fi
else
echo "current branch isn't int1177/next"
fi
Actually, this particular problem is not a bash issue, but rather a Git issue.
Why doesn't "cd" work in a shell script? is valid in general, and is a suitable answer to many other questions. But this particular post-commit hook is trying to chdir out of a submodule into its parent superproject, then make a commit within the parent superproject. That is possible. It may be a bad idea for other reasons—in general it's unwise to have Git commit hooks create commits, even in other repositories1—but in this particular case you're running into the fact that Git finds its directories through environment variables.
In particular, there's an environment variable GIT_DIR that tells Git: The .git directory containing the repository is at this path. When Git runs a Git hook, Git typically sets $GIT_DIR to . or .git. If $GIT_DIR is not set, Git will find the .git directory by means of a directory-tree search, but if $GIT_DIR is set, Git assumes that $GIT_DIR is set correctly.
The solution is to unset GIT_DIR:
unset GIT_DIR
cd ..
The rest of the sub-shell commands will run in the one-step-up directory, and now that $GIT_DIR is no longer set, Git will search the superproject's work-tree for the .git directory for the superproject.
As an aside, this:
$(git branch | grep \* | cut -d ' ' -f2)
is a clumsy way to get the name of the current branch. Use:
git rev-parse --abbrev-ref HEAD
instead, here. (The other option is git symbolic-ref --short HEAD but that fails noisily with a detached HEAD, while you probably want the quiet result to be just the word HEAD, which the rev-parse method will produce.)
1The main danger in this case is that the superproject repository is not necessarily in any shape to handle a commit right now. Edit: or, as discovered in this comment, is not even set up to be a superproject for that submodule, yet, much less to have a submodule-updating commit added.

Cannot suppress git branch error when not in a git repository

I would like my command prompt to display the current branch in my Prompt String 1 (PS1). The command works in git repositories, but when not in a git repo, I get the rightful error message: fatal: Not a git repository (or any of the parent directories): .git
I would like to suppress that error message otherwise every time I switch directories and I am not in a git repo, that error is printed to the terminal.
I read up on suppressing terminal output by sending error output to the null device /dev/null, but the error message still prints in my terminal.
Here is the command I am using to extract the current branch:
git branch 2>/dev/null | grep '*' | cut -d ' ' -f2.
Make sure to escape the $ in the $() construct, so that it will be evaluated anew when each prompt is generated instead of only when the PS1 variable is set.
Here's what it looks like for me in practice:
# Set PS1
$ PS1="\$(git branch 2>/dev/null | grep '*' | cut -d ' ' -f 2) $ "
# Currently in directory that is not a Git repository, change into one.
$ cd dotfiles/
# Git branch is then displayed in the prompt, leave the directory.
master $ cd ..
# No git branch displayed, change back into it for good measure.
$ cd dotfiles/
# Branch is displayed again.
master $

Pre-commit hook to check for Jira issue key

I am looking for somehelp to write a pre-commit hook on windows to check for Jira issue key while commiting.Commit should not be allowed if Jira key is not present.I couldnt find any way.I am new to scripting.Any help would be highly appreciated.
I assume you are talking about a hooks in a Git repository.
Navigate to your local Git repository and go into the folder .git\hooks
Create a file named commit-msg
Insert the following content (no idea how to format it correctly)
#!/bin/bash
# The script below adds the branch name automatically to
# every one of your commit messages. The regular expression
# below searches for JIRA issue key's. The issue key will
# be extracted out of your branch name
REGEX_ISSUE_ID="[a-zA-Z0-9,\.\_\-]+-[0-9]+"
# Find current branch name
BRANCH_NAME=$(git symbolic-ref --short HEAD)
if [[ -z "$BRANCH_NAME" ]]; then
echo "No branch name... "; exit 1
fi
# Extract issue id from branch name
ISSUE_ID=$(echo "$BRANCH_NAME" | grep -o -E "$REGEX_ISSUE_ID")
echo "$ISSUE_ID"': '$(cat "$1") > "$1"
If you have now a branch named like feature/MYKEY-1234-That-a-branch-name
and add as commit message "Add a new feature"
Your final commit message will look like
MYKEY-1234: Add a new feature
You can put the hook globally when using Git 2.9.
Please find here further useful information:
https://andy-carter.com/blog/automating-git-commit-messages-with-git-hooks
Git hooks : applying `git config core.hooksPath`
You have to put the following script in your local Git repository at .git/hooks/prepare-commit-msg. This will be run whenever you add a new commit.
#!/bin/bash
# get current branch
branchName=`git rev-parse --abbrev-ref HEAD`
# search jira issue id in pattern
jiraId=$(echo $branchName | sed -nr 's,[a-z]*\/*([A-Z]+-[0-9]+)-.+,\1,p')
# only prepare commit message if pattern matched and jiraId was found
if [[ ! -z $jiraId ]]; then
# $1 is the name of the file containing the commit message
sed -i.bak -e "1s/^/\n\n$jiraId: /" $1
fi
First, we get the branch name, for example feature/JIRA-2393-add-max-character-limit.
Next, we extract the key, removing the prefix feature.
The resulting commit message will be prefixed by "JIRA-2393: "
The script also works when there is no prefix, e.g. without feature/, bugfix/, etc.
You can use git server-side pre-receive hook.
https://git-scm.com/docs/git-receive-pack
In the code below for a successful push, you must specify the Jira issue key in the comment for commit.
#!/bin/bash
#
# check commit messages for JIRA issue numbers
# This file must be named pre-receive, and be saved in the hook directory in a bare git repository.
# Run "chmod +x pre-receive" to make it executable.
#
# Don't forget to change
# - Jira id regex
jiraIdRegex="\[JIRA\-[0-9]*\]"
error_msg="[POLICY] The commit doesn't reference a JIRA issue"
while read oldrev newrev refname
do
for sha1Commit in $(git rev-list $oldrev..$newrev);
do
echo "sha1 : $sha1Commit";
commitMessage=$(git log --format=%B -n 1 $sha1Commit)
jiraIds=$(echo $commitMessage | grep -Pqo $jiraIdRegex)
if ! jiraIds; then
echo "$error_msg: $commitMessage" >&2
exit 1
fi
done
done
exit 0

How can I display the current branch and folder path in terminal?

I've been watching some of the Team Treehouse videos and they have a very nice looking terminal when working with Git.
For example they have (something similar):
mike#treehouseMac: [/Work/test - feature-branch-name] $ git add .
mike#treehouseMac: [/Work/test - feature-branch-name] $ git commit -m "Some feature."
mike#treehouseMac: [/Work/test - feature-branch-name] $ git checkout master
mike#treehouseMac: [/Work/test - master] $ git status
How can my terminal show me some useful information of what branch I'm on, with colors to distinguish bits of the data I want? Is there some sort of de-facto plugin I haven't found yet?
I'm using Mac OSX 10.8
For anyone looking for how to do this in macOS Catalina or above (10.15+ incl. Big Sur 11.0) which has deprecated bash in favour of zsh, here is my .zshrc file:
parse_git_branch() {
git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}
COLOR_DEF='%f'
COLOR_USR='%F{243}'
COLOR_DIR='%F{197}'
COLOR_GIT='%F{39}'
NEWLINE=$'\n'
setopt PROMPT_SUBST
export PROMPT='${COLOR_USR}%n#%M ${COLOR_DIR}%d ${COLOR_GIT}$(parse_git_branch)${COLOR_DEF}${NEWLINE}%% '
If you don't like the colours I have used, replace the 243/197/39 values with the colour codes as defined here:
https://misc.flogisoft.com/bash/tip_colors_and_formatting
Simple way
Open ~/.bash_profile in your favorite editor and add the following content to the bottom.
Git branch in prompt.
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u#\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "
Add Git Branch To Terminal Prompt (Mac)
It's not about a plugin. It's about prompt tricks in the shell.
For a cool setup in bash, check out the dotfiles project of this guy:
https://github.com/mathiasbynens/dotfiles
To get a fancy prompt, include the .bash_prompt in your ~/.bash_profile or ~/.bashrc.
To get the exact same prompt as in your question, change the export PS1 line at the end of .bash_prompt like this:
export PS1="\[${BOLD}${MAGENTA}\]\u\[$WHITE\]#\[$ORANGE\]\h\[$WHITE\]: [\[$GREEN\]\w\[$WHITE\]\$([[ -n \$(git branch 2> /dev/null) ]] && echo \" - \")\[$PURPLE\]\$(parse_git_branch)\[$WHITE\]] \$ \[$RESET\]"
I ended up using all the .bash* files from this repository about a month ago, and it's been really useful for me.
For Git, there are extra goodies in .gitconfig.
And since you're a mac user, there are even more goodies in .osx.
To expand on the existing great answers, a very simple way to get a great looking terminal is to use the open source Dotfiles project.
https://github.com/mathiasbynens/dotfiles
Installation is dead simple on OSX and Linux. Run the following command in Terminal.
git clone https://github.com/mathiasbynens/dotfiles.git && cd dotfiles && source bootstrap.sh
This is going to:
Git clone the repo.
cd into the folder.
Run the installation bash script.
For Mac Catilina 10.15.5 and later version:
add in your ~/.zshrc file
function parse_git_branch() {
git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}
setopt PROMPT_SUBST
export PROMPT='%F{grey}%n%f %F{cyan}%~%f %F{green}$(parse_git_branch)%f %F{normal}$%f '
My prompt includes:
Exit status of last command (if not 0)
Distinctive changes when root
rsync-style user#host:pathname for copy-paste goodness
Git branch, index, modified, untracked and upstream information
Pretty colours
Example:
To do this, add the following to your ~/.bashrc:
#
# Set the prompt #
#
# Select git info displayed, see /usr/share/git/completion/git-prompt.sh for more
export GIT_PS1_SHOWDIRTYSTATE=1 # '*'=unstaged, '+'=staged
export GIT_PS1_SHOWSTASHSTATE=1 # '$'=stashed
export GIT_PS1_SHOWUNTRACKEDFILES=1 # '%'=untracked
export GIT_PS1_SHOWUPSTREAM="verbose" # 'u='=no difference, 'u+1'=ahead by 1 commit
export GIT_PS1_STATESEPARATOR='' # No space between branch and index status
export GIT_PS1_DESCRIBE_STYLE="describe" # detached HEAD style:
# contains relative to newer annotated tag (v1.6.3.2~35)
# branch relative to newer tag or branch (master~4)
# describe relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
# default exactly eatching tag
# Check if we support colours
__colour_enabled() {
local -i colors=$(tput colors 2>/dev/null)
[[ $? -eq 0 ]] && [[ $colors -gt 2 ]]
}
unset __colourise_prompt && __colour_enabled && __colourise_prompt=1
__set_bash_prompt()
{
local exit="$?" # Save the exit status of the last command
# PS1 is made from $PreGitPS1 + <git-status> + $PostGitPS1
local PreGitPS1="${debian_chroot:+($debian_chroot)}"
local PostGitPS1=""
if [[ $__colourise_prompt ]]; then
export GIT_PS1_SHOWCOLORHINTS=1
# Wrap the colour codes between \[ and \], so that
# bash counts the correct number of characters for line wrapping:
local Red='\[\e[0;31m\]'; local BRed='\[\e[1;31m\]'
local Gre='\[\e[0;32m\]'; local BGre='\[\e[1;32m\]'
local Yel='\[\e[0;33m\]'; local BYel='\[\e[1;33m\]'
local Blu='\[\e[0;34m\]'; local BBlu='\[\e[1;34m\]'
local Mag='\[\e[0;35m\]'; local BMag='\[\e[1;35m\]'
local Cya='\[\e[0;36m\]'; local BCya='\[\e[1;36m\]'
local Whi='\[\e[0;37m\]'; local BWhi='\[\e[1;37m\]'
local None='\[\e[0m\]' # Return to default colour
# No username and bright colour if root
if [[ ${EUID} == 0 ]]; then
PreGitPS1+="$BRed\h "
else
PreGitPS1+="$Red\u#\h$None:"
fi
PreGitPS1+="$Blu\w$None"
else # No colour
# Sets prompt like: ravi#boxy:~/prj/sample_app
unset GIT_PS1_SHOWCOLORHINTS
PreGitPS1="${debian_chroot:+($debian_chroot)}\u#\h:\w"
fi
# Now build the part after git's status
# Highlight non-standard exit codes
if [[ $exit != 0 ]]; then
PostGitPS1="$Red[$exit]"
fi
# Change colour of prompt if root
if [[ ${EUID} == 0 ]]; then
PostGitPS1+="$BRed"'\$ '"$None"
else
PostGitPS1+="$Mag"'\$ '"$None"
fi
# Set PS1 from $PreGitPS1 + <git-status> + $PostGitPS1
__git_ps1 "$PreGitPS1" "$PostGitPS1" '(%s)'
# echo '$PS1='"$PS1" # debug
# defaut Linux Mint 17.2 user prompt:
# PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u#\h\[\033[01;34m\] \w\[\033[00m\] $(__git_ps1 "(%s)") \$ '
}
# This tells bash to reinterpret PS1 after every command, which we
# need because __git_ps1 will return different text and colors
PROMPT_COMMAND=__set_bash_prompt
In 2019, I think git branch --show-current is a better command than the accepted answer.
$ git branch --show-current
master
(Added in git 2.22 release in June 2019)
It runs much faster as it doesn't need to iterate through all branches. Similarly git branch should be avoided too in the command prompt as it slows down your prompt if you have many local branches.
Put it in a function to use anywhere on command prompt:
# This function returns '' in all below cases:
# - git not installed or command not found
# - not in a git repo
# - in a git repo but not on a branch (HEAD detached)
get_git_current_branch() {
git branch --show-current 2> /dev/null
}
More context:
$ git version
git version 2.23.0
Just Install the oh-my-zsh plugins as described in this link.
It works best on macOS and Linux.
Basic Installation
Oh My Zsh is installed by running one of the following commands in your terminal. You can install this via the command-line with either curl or wget.
via curl
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
via wget
sh -c "$(wget https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O -)"
for anyone still looking for this , i just installed ohmyz
https://ohmyz.sh/#install and the branches it's showing
In the new Catalina OS for Mac
i) zsh way. Add below lines in .zshrc
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ \1/'
}
COLOR_DEF='%f'
COLOR_DIR='%F{197}'
COLOR_GIT='%F{33}'
setopt PROMPT_SUBST
export PROMPT='${COLOR_DIR}%1d${COLOR_DEF}${COLOR_GIT}$(parse_git_branch)${COLOR_DEF} $ '
ii) Or to use old bash, you need to change
System Preference -> Users & Groups -> Right click user user
-> Advanced Option -> Login shell -> /bin/bash
Write .bash_profile as below and restart the system
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ \1/'
}
export PS1="\W\[\033[33m\]\$(parse_git_branch)\[\033[00m\] $ "
Output: FolderName BranchName $
The git package installed on your system includes bash files to aid you in creating an informative prompt. To create colors, you will need to insert terminal escape sequences into your prompt. And, the final ingredient is to update your prompt after each command gets executed by using the built-in variable PROMPT_COMMAND.
Edit your ~/.bashrc to include the following, and you should get the prompt in your question, modulo some color differences.
#
# Git provides a bash file to create an informative prompt. This is its standard
# location on Linux. On Mac, you should be able to find it under your Git
# installation. If you are unable to find the file, I have a copy of it on my GitHub.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-git-prompt.sh
#
source /usr/share/git/completion/git-prompt.sh
#
# Next, we need to define some terminal escape sequences for colors. For a fuller
# list of colors, and an example how to use them, see my bash color file on my GitHub
# and my coniguration for colored man pages.
#
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/10-colors.sh
# https://github.com/chadversary/home/blob/42cf697ba69d4d474ca74297cdf94186430f1384/.config/kiwi-profile/40-less.sh
#
color_start='\e['
color_end='m'
color_reset='\e[0m'
color_bg_blue='44'
#
# To get a fancy git prompt, it's not sufficient to set PS1. Instead, we set PROMPT_COMMAND,
# a built in Bash variable that gets evaluated before each render of the prompt.
#
export PROMPT_COMMAND="PS1=\"\${color_start}\${color_bg_blue}\${color_end}\u#\h [\w\$(__git_ps1 \" - %s\")]\${color_reset}\n\$ \""
#
# If you find that the working directory that appears in the prompt is ofter too long,
# then trim it.
#
export PROMPT_DIRTRIM=3
There are many PS1 generators but ezprompt has the git status (2nd tab 'Status Elements' ) also.
For macOS:
Step 1:
Create and edit a .zshrc file that will be used for terminal configuration.
touch ~/.zshrc; open ~/.zshrc
Step 2:
Add this to your ~/.zshrc file:
function parse_git_branch() {
git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}
setopt PROMPT_SUBST
export PROMPT='%F{grey}%n%f %F{cyan}%~%f %F{green}$(parse_git_branch)%f %F{normal}$%f '
Based on 6LYTH3's answer I've decided to post my own due to some improvements that may come in handy:
Simple solution
Open ~/.bash_profile and add the following content
# \[\e[0m\] resets the color to default color
reset_color='\[\e[0m\]'
# \[\033[33m\] sets the color to yellow
path_color='\[\033[33m\]'
# \e[0;32m\ sets the color to green
git_clean_color='\[\e[0;32m\]'
# \e[0;31m\ sets the color to red
git_dirty_color='\[\e[0;31m\]'
# determines if the git branch you are on is clean or dirty
git_prompt ()
{
# Is this a git directory?
if ! git rev-parse --git-dir > /dev/null 2>&1; then
return 0
fi
# Grab working branch name
git_branch=$(git branch 2>/dev/null| sed -n '/^\*/s/^\* //p')
# Clean or dirty branch
if git diff --quiet 2>/dev/null >&2; then
git_color="${git_clean_color}"
else
git_color="${git_dirty_color}"
fi
echo " [$git_color$git_branch${reset_color}]"
}
export PS1="${path_color}\w\[\e[0m\]$(git_prompt)\n"
This should:
1) Prompt the path you're in, in color: path_color.
2) Tell you which branch are you.
3) Color the name of the branch based on the status of the branch with git_clean_color
for a clean work directory and git_dirty_color for a dirty one.
4) The brackets should stay in the default color you established in your computer.
5) Puts the prompt in the next line for readability.
You can customize the colors with this list
Sophisticated Solution
Another option is to use Git Bash Prompt, install with this. I used the option via Homebrew on Mac OS X.
git_prompt_list_themes to see the themes but I didn't like any of them.
git_prompt_color_samples to see available colors.
git_prompt_make_custom_theme [<Name of base theme>] to create a new custom theme, this should create a .git-prompt-colors.sh file.
subl ~/.git-prompt-colors.sh to open git-prompt-colors.sh and customize:
The .git-prompt-colors.sh file should look like this with my customization
override_git_prompt_colors() {
GIT_PROMPT_THEME_NAME="Custom"
# Clean or dirty branch
if git diff --quiet 2>/dev/null >&2; then
GIT_PROMPT_BRANCH="${Green}"
else
GIT_PROMPT_BRANCH="${Red}"
fi
}
reload_git_prompt_colors "Custom"
Hope this helps, have a great day!
In Catalina and above, you can open your .zshrc file by running nano ~/.zshrc, and posting the following at the top of the document:
# Show git branch in terminal
function parse_git_branch() {
git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}
COLOR_DEF=$'\e[0m'
COLOR_USR=$'\e[38;5;243m'
COLOR_DIR=$'\e[38;5;220m’
COLOR_GIT=$'\e[38;5;39m'
setopt PROMPT_SUBST
export PROMPT='${COLOR_USR}%n ${COLOR_DIR}%~
${COLOR_GIT}$(parse_git_branch)${COLOR_DEF} $ '
Exit and save. Restart your terminal, or run exec zsh and that should be it.
OR
You can check out this theme and see if you like it. It is really easy to install and looks good in my opinion:
https://github.com/romkatv/powerlevel10k#configuration
Hope that helps.
From Mac OS Catalina
.bash_profile is replaced with .zprofile
Step 1:
Create a .zprofile
touch .zprofile
Step 2:
nano .zprofile
type below line in this
source ~/.bash_profile
and save(ctrl+o return ctrl+x)
Step 3:
Restart your terminal
To Add Git Branch Name
Now you can add below lines in .bash_profile
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u#\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "
Restart your terminal this will work.
Note:
Even you can rename .bash_profile to .zprofile that also works.
Keep it fast, keep it simple
put this in your ~/.bashrc file.
git_stuff() {
git_branch=$(git branch --show-current 2> /dev/null)
if [[ $git_branch == "" ]];then
echo -e ""
elif [[ $git_branch == *"Nocommit"* ]];then
echo -e "No commits"
else
echo -e "$git_branch"
fi
}
prompt() {
PS1="\e[2m$(date +%H:%M:%S.%3N) \e[4m$(git_stuff)\033[0m\n\w$ "
}
PROMPT_COMMAND=prompt
Then source ~/.bashrc
Did some searching & then adjusted it a bit & settled with this.
vi ~/.zshrc
And within zshrc file ->
function git_branch_name()
{
branch=$(git symbolic-ref HEAD 2> /dev/null | awk 'BEGIN{FS="/"} {print $NF}')
if [[ $branch == "" ]];
then
:
else
echo '- ('$branch')'
fi
}
setopt prompt_subst
prompt='%n %1/ $(git_branch_name) $ '

Resources