Effortless Git Repo Switching with a Simple Bash Function!
12 February 2025 at 10:36
Why I Created This Function
At first, I used an alias
alias gitdir="cd ~/Git/"
(This means gitdir
switches to the ~/Git/
directory, but I wanted it to switch directly to a repository.)
So, I wrote a Bash function.

Write Code to .bashrc
File
The .bashrc
file runs when a new terminal window is opened.
So, we need to write the function inside this file.
Code
gitrepo() {
# Exact Match
repoList=$(ls $HOME/Git)
if [ -n "$(echo "$repoList" | grep -w $1)" ]; then
cd $HOME/Git/$1
else
# Relevant Match
getRepoName=$(echo "$repoList" | grep -i -m 1 $1)
if [ -n "$getRepoName" ]; then
cd "$HOME/Git/$getRepoName"
else
echo "Repository Not Founded"
cd $HOME/Git
fi
fi
}
Code Explanation
The $repoList
variable stores the list of directories inside the Git folder.
Function Logic Has Two Parts:
- Exact Match
- Relevant Match
Exact Match
if [ -n "$(echo "$repoList" | grep -w $1)" ]; then
cd $HOME/Git/$1
If condition: The $repoList
variable parses input for grep.
- grep -w matches only whole words.
$1
is the functionβs argument in bash.- -n checks if a variable is not empty. Example syntax:
[ a != "" ]
is equivalent to[ -n a ]

Relevant Match
getRepoName=$(echo "$repoList" | grep -i -m 1 $1)
if [ -n "$getRepoName" ]; then
cd "$HOME/Git/$getRepoName"
Relevant search: If no Exact Match is found, this logic is executed next.
getRepoName="$repoList" | grep -i -m 1 $1
-i
ignores case sensitivity.-m 1
returns only the first match.
Example of -m with grep:ls | grep i3
It returns i3WM and i3status, but -m 1
ensures only i3WM is selected.

No Match
If no match is found, it simply changes the directory to the Git folder.
else
echo "Repository Not Founded"
cd $HOME/Git

What I Learned
- Basics of Bash functions
- How to use
.bashrc
and reload changes.