A use case for bash functions with git on Windows

When you open a Git Bash shell, it will typically open under your home directory, as indicated by a yellow tilda (~) at the end of the command line.

Side-note tip if you’re new to unix type shells:
~ refers back to your home directory – e.g. C:\users\YourUserName\ under Windows, so entering cd ~/SomeDirectory from any location will always change your current dir back to c:\users\SomeDirectory.

For my part, I’ve got most of my projects and source code under a directory called “source“, and all my git-projects below that again in a directory called repos. This means that each time I open the git shell to do any work, the first thing I need to do is change directory using: cd source/repos/TargetRepo where TargetRepo would be the name of a given project.

This is not a big deal, but it would be better if I could simplify the process of moving to whichever project I wanted to. I could do just that thanks to this simple solution found on Stack Overflow (new window). I’m expanding slightly on it here so I know I’ll find it if I need it again, and because I’m convinced it can be useful to others too.

Bash Functions

Bash functions can be written in your .bash_profile file, located in your home directory. If you can’t find it, you can create it e.g. using:

cd ~
touch .bash_profile

Here’s the function as applied to the scenario described above:

    if [ "$1" ]; then
      cd "${dir}/${1}"
      cd "${dir}"

So what does this do? Well it defines the command repos, which when run without any arguments, will change the current directory to ~/source/repos. If any argument is added, then it will try to change the directory into a directory with that name, located under ~/source/repos.

Note that this will work from any directory, so whether my current location is ~/some/long/path/wherever, or /c/Windows, the following will work:

Change the current directory to ~/source/repos:


Change the current directory to ~/source/repos/myCurrentProject:

repos myCurrentProject

Engage and contribute for the common benefit of mankind!

This site uses Akismet to reduce spam. Learn how your comment data is processed.