Akash's Blog

_

Showing posts with label crontab. Show all posts
Showing posts with label crontab. Show all posts

Thursday, January 23, 2025

Auto push to Git on Mac

Introduction

For periodically syncing changes of your Github repository you can automate the process using a script and crontab on Mac OS. It's really quick and simple if you don't have more complex requirements. Note taking is one of the use cases where you want periodic sync to take place automatically to ensure notes are pushed to the cloud without any manual steps.

Setup

1. Open terminal and type crontab -e this will open an editor where you can specify which script to execute, here we want to push our changes so we will point it to that script. Here we have used cron expression "* */2 * * *" which will execute the script every two hours. You can use crontab.guru to generate the expression as per your requirement.

* */2 * * * /path/to/sync.sh >> /path/to/logs/run.logs 2>&1

Save the changes. (Type :wq! to save) 

File sync.sh should be accessible and hold required permissions. Use chmod command to update the permission to necessary state.















2. Define sync.sh in following way to push your changes. Prerequisite is that you have cloned and setup required github repository in respective folder.

#!/bin/bash

set -e

cd /path/to/repo

BRANCH="main"
COMMIT_MSG=${1:-"Update"}

 if [[ -n $(git status --porcelain) ]]; then
    echo "Changes detected."
    git add -A
    git commit -m "$COMMIT_MSG"
    git push origin "$BRANCH"
    echo "Changes pushed successfully!"
else
    echo "No changes to commit."
fi

Important Note
Note that this script syncs all the changes of given repository. Do not add sensitive information like credentials, tokens or anything which you do not want to get synced especially on public repository if that is the case.
↑ Back to Top