BASH
Check Git Status and Pull Latest Changes
Automate checking the Git status of a repository for uncommitted changes or untracked files, and pull the latest changes from a specified branch, ensuring your repo is up-to-date.
#!/bin/bash
REPO_PATH=${1:-.}
BRANCH_NAME=${2:-main}
cd "$REPO_PATH" || { echo "Error: Repository path not found."; exit 1; }
echo "Checking Git status for $(pwd) on branch $BRANCH_NAME..."
# Check for uncommitted changes
if ! git diff-index --quiet HEAD --;
then
echo "Warning: Uncommitted changes detected. Please commit or stash them first."
# Optionally, exit or handle these changes
# exit 1
fi
# Check for untracked files
if [ -n "$(git status --porcelain | grep '^??')" ];
then
echo "Warning: Untracked files detected."
# Optionally, exit or handle these changes
# exit 1
fi
# Fetch latest changes
git fetch origin
# Compare local and remote
LOCAL=$(git rev-parse HEAD)
REMOTE=$(git rev-parse @{u})
BASE=$(git merge-base HEAD @{u})
if [ "$LOCAL" = "$REMOTE" ]; then
echo "Repository is up-to-date."
elif [ "$LOCAL" = "$BASE" ]; then
echo "Pulling latest changes from $BRANCH_NAME..."
git pull origin "$BRANCH_NAME"
elif [ "$REMOTE" = "$BASE" ]; then
echo "Local repository is ahead of remote."
else
echo "Repository has diverged. Manual intervention required."
fi
How it works: This script navigates to a Git repository, performs checks for uncommitted changes or untracked files, and then fetches updates from the remote. It compares the local branch with its upstream counterpart to determine if a pull is needed, if the local is ahead, or if a divergence has occurred. This is useful for automating deployment pre-checks or keeping development environments synchronized.