Select Page

Check Bash Script Location in Git Repo Root Directory

by | Jan 11, 2023 | Miscellaneous | 0 comments

Have you ever run a Bash script in a Git repository, only to find out later that it was not being run from the root directory of the repository? This can cause issues with the script’s functionality and make it difficult to troubleshoot.

To avoid this problem, you can add a simple check to your Bash script to verify that it is being run from the root directory of the Git repository. In this blog post, we’ll walk through the steps to create a Bash script that performs this check.

Step 1: Open a text editor

Open a text editor such as nano, vim or Emacs. For the purpose of this example, we’ll use nano.

nano check-git-root.sh

Step 2: Add the Bash script code

Add the following Bash script code to your text editor: 

check-git-root.sh

#!/bin/bash

if [ "$(git rev-parse --show-toplevel)" != "$(pwd)" ]; then
  echo "Error: This script must be run from the root directory of a Git repository."
  exit 1
fi

echo "This script is being run from the root directory of a Git repository."

This script uses the git rev-parse –show-toplevel command to get the top-level directory of the Git repository, and compares it to the current working directory (pwd). If they are not the same, it prints an error message and exits with a non-zero status. If they are the same, it prints a success message.

Step 3: Save and exit the file

Save the file by pressing Ctrl + O and then exit by pressing Ctrl + X.

Step 4: Make the script executable

Make the script executable with the following command:

chmod +x check-git-root.sh

This command gives the owner of the file execute permission, allowing them to run the script.

Step 5: Run the script

Run the script with the following command:

./check-git-root.sh

This will check whether the script is being run from the root directory of a Git repository. If it is, you will see the message “This script is being run from the root directory of a Git repository.” If it is not, you will see the error message “Error: This script must be run from the root directory of a Git repository.”.

In conclusion, by adding this simple check to your Bash scripts, you can ensure that they are being run from the correct directory and avoid issues with their functionality.

Kirk Makse
Author: Kirk Makse

Greetings, my name is Kirk. I’m the creator of Rails Zone and a passionate Ruby on Rails developer. During my free time, I develop helpful tools and tutorials that aid fellow Ruby on Rails developers in creating applications with improved efficiency and speed.