Last active
March 14, 2019 02:42
-
-
Save ashtonmeuser/790cf0ff8c37df8ac4d351f461f6b88b to your computer and use it in GitHub Desktop.
Stage, commit, and push changed files in git repository
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| usage() { | |
| echo "Usage: $0 [-d <string>] [-u] [-r] [-h]" 1>&2 | |
| echo "-d Directory of target repository, defaults to working directory" 1>&2 | |
| echo "-u Consider untacked files" 1>&2 | |
| echo "-r Do not push to remote repository" 1>&2 | |
| echo "-h Show usage manual" 1>&2 | |
| exit 1 | |
| } | |
| REPO_DIR="." # Default to working dir | |
| UNTRACKED="no" # Default to NOT considering untracked files | |
| REMOTE=true # Default to pushing to remote | |
| while getopts ":d:urh" OPTION; do | |
| case "$OPTION" in | |
| d) REPO_DIR="$OPTARG";; | |
| u) UNTRACKED="all";; | |
| r) REMOTE=false;; | |
| *) usage;; | |
| esac | |
| done | |
| if [[ ! -d "$REPO_DIR" ]]; then # Ensure valid directory | |
| echo "Directory '$REPO_DIR' does not exist" 1>&2 | |
| exit 1 | |
| fi | |
| cd "$REPO_DIR" # Navigate to repo dir | |
| GIT_DIFF="$(git status --porcelain --untracked-files="$UNTRACKED" 2>/dev/null)" | |
| if [[ $? -ne 0 ]]; then # Ensure directory contains git repo | |
| echo "Directory '$REPO_DIR' does not contain git repository" 1>&2 | |
| exit 1 | |
| fi | |
| DIFF_COUNT="$(echo -n "$GIT_DIFF" | grep -c '^')" # Count number of modified files | |
| if [[ $DIFF_COUNT -le 0 ]]; then # Nothing to commit | |
| echo "No uncommitted changes in repository" 1>&2 | |
| exit 1 | |
| fi | |
| echo "Found $DIFF_COUNT uncommitted file change(s) in repository" | |
| MESSAGE="Automatic commit $(date +'%Y-%m-%d %T')" # Form commit message | |
| echo "Committing with message '$MESSAGE'" | |
| git add -A &> /dev/null # Stage all files | |
| git commit -m "$MESSAGE" --quiet &> /dev/null # Commit with message | |
| if [ $? -ne 0 ]; then # Commit failed | |
| echo "Failed to commit changes to repository" 1>&2 | |
| exit 1 | |
| fi | |
| HASH="$(git rev-parse HEAD)" # Get hash of latest local commit | |
| echo "Committed with hash $HASH" | |
| if [[ "$REMOTE" = false ]]; then # Skip remote push argument set | |
| echo "Skipping push to remote repository" | |
| exit 0 | |
| fi | |
| git push --quiet &> /dev/null # Push to remote repo | |
| if [ $? -ne 0 ]; then # Push failed | |
| echo "Failed to push to remote repository" 1>&2 | |
| exit 1 | |
| fi | |
| echo "Pushed to remote repository" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment