Search code examples
bashgitmacoscron

fatal: could not read Username When pushing to git using a cron job


Hey I am trying to push code to git using a cron job on the Mac. I edit my crontab using crontab -e and have the following inside:

* 12 * * 1 ~/Dropbox/MD/sync.sh
* 12 * * 5 ~/Dropbox/MD/sync.sh

The script is as follows:

#!/bin/bash

cd ~/Dropbox/MD
/usr/bin/git add .
/usr/bin/git commit -m "Docs auto update"
/usr/bin/git push origin master

However the command fails and when I run mail I can check the error message which is: fatal: could not read Username for 'https://github.com': Device not configured. How can I fix this issue? If I run the commands manually from the terminal I have no issues and I am not prompted for user credentials.

Any pointers on this would be much appreciated. Thanks!


Solution

  • When automating git tasks using SSH keys is recommended. You can setup SSH keys with push access by following these steps:

    1. get the SSH key of the user(or generate one: ssh-keygen -t rsa -b 4096 -C "[email protected]")
    2. copy contents of the public key (cat ~/.ssh/id_rsa.pub)
    3. Go to the project on github.com
    4. Go to project settings
    5. Choose Deploy Keys (https://github.com/user/project/settings/keys)
    6. Choose add deploy key
    7. Add your public key contents
    8. Check Allow write access
    9. Choose Add Key

    Please note this will only work for repositories cloned with the following remote: [email protected]:user/project.git

    The remote can be updated wit the following steps:

    1. go to the repository folder on the server
    2. run git remote remove origin
    3. run git remote add origin [email protected]/project.git