Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for the presence of a git repository in a directory using bash script

Tags:

git

linux

bash

I am trying to work with git on my project.

I want to set up the terminal such that whenever I cd into a directory that contains a git project, the terminal should indicate which git branch I am currently on.

If there is a git project, the terminal show only the name of the branch, for example

(master) $

otherwise it should show the current directory path.i.e

username@machinename:path/to/directory $

I found a similar question answered here but i don't know how to modify the answer to suit my need, because am not good with bash scripting. Any suggestion will be highly appreciated.

like image 356
Desmoline Awa Avatar asked Nov 17 '25 08:11

Desmoline Awa


1 Answers

Have a look at this project https://github.com/jimeh/git-aware-prompt, it should solve your whole problem and when not, you can change it to meet your needs. Main logic is in prompt.sh.

To find current git branch name in directory, you can always run

git rev-parse --abbrev-ref HEAD

It will return branch name, HEAD (when detached) or nothing when directory is not par of git repository. If you need only this information, you can update your .bashrc. Edit variable PS1, which is bash prompt format.

PS1='(`git rev-parse --abbrev-ref HEAD 2> /dev/null`) \$ '

This is example how to display branch name anywhere in the prompt. The git script will help you and recognize whether to show branch or directory. It will update your PROMPT_COMMAND, which is called every time the bash prompt line is displayed, by checking for git branch name which you can then use in PS1 as a variable. You can then update your existing PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ ' to

PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w \(\$git_branch\)\$ '
like image 55
martin.malek Avatar answered Nov 19 '25 05:11

martin.malek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!