I’m using Git, I’ve changed the following line in .bashrc, To show the current checkedout branch in prompt, when pwd is a Git Repo. Operating System I’m using is: Ubuntu 32bit
# Original PS1 Line
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
I’m using this line to display current branch of git repo in shell prompt, instead of, the above line.
# PS1 Line to show current Git Branch in the Prompt
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\[\033[01;32m\]$(__git_ps1 " (%s)")\[\033[00m\]\$ '
The Problem is when I give it to friends, Shell gives error __git_ps1: command not found, while navigating between directories, as the script checks for git branch on changing directories.
How do I check if Git is installed and perform the branch check only if git is installed?
Edit:
As suggested by ayckoster, I cameup with the following lines of code:
if [ "$color_prompt" = yes ]; then
git --version
GIT_IS_AVAILABLE=$?
if [ $GIT_IS_AVAILABLE -eq 0 ]; then
# PS1 Line to show current Git Branch in the Prompt
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\[\033[01;32m\]$(__git_ps1 " (%s)")\[\033[00m\]\$ '
else
# Original PS1 Line
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
fi
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
Now, Everytime I open the terminal I get the git --version outputted to screen, while Git is installed, and I get the following error, while opening terminal when Git is not installed:
The program 'git' is currently not installed. You can install it by typing:
sudo apt-get install git
How do I clear this? Thanks.
Final Edit:
This is the code I came up with finally, Feel Free to use this code in your .bashrc to display current git branch in your shell prompt
if [ "$color_prompt" = yes ]; then
if git --version &>/dev/null; then
# PS1 Line to show current Git Branch in the Prompt
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\[\033[01;32m\]$(__git_ps1 " (%s)")\[\033[00m\]\$ '
else
# Original PS1 Line
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
fi
else
if git --version &>/dev/null; then
# PS1 Line to show current Git Branch in the Prompt
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w $(__git_ps1 "(%s)")\$ '
else
# Original PS1 Line
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
fi
Try to execute
Depending on the return value
$?you can assume git is installed or not. If you get 0 everything is fine otherwise git is not installed. You can alsotestthis.This assumes everything is setup correctly and git is in your $PATH and the git command is not renamed.
Use it like this