LoginSignup
4
2

More than 3 years have passed since last update.

gitに自動pushする方法

Last updated at Posted at 2020-10-18

はじめに

私はAtCoderの過去問を解いたらそのソースコードをgithubにpushしています。
毎回同じコマンドを打つのはめんどくさいので、Macでlinux系のコマンドcrontabを使用してgit pushを自動化しました。

crontabとは

決まった時間に自動的にコマンドを使用してくれるデーモンプロセスです。

crontab -eでコマンドの登録をします。

分 時 日 月 曜日 コマンド
*  *  *  *  *  some_commands

*はワイルドカードを意味しています。

例えば、以下のようにすると、毎日20時0分にechoしてくれます

分 時 日 月 曜日 コマンド
0  20  *  *  *  echo "Hello World!"

Macでの注意点

私はmacOS 10.15.5 catalinaを使用しているのですがこのままだとcrontabが動かないので、
フルディスクアクセスにcronを追加しましょう。
このサイトのやり方が参考になります。

crontabにgit pushを登録

SSH のラッパースクリプト(git_ssh.sh)を作成します。

git_ssh.sh
#!/bin/bash

exec ssh -o IdentityFile=/path/to/id_git_rsa "$@"

秘密鍵とシェルスクリプトのパーミッションを変更します。
こうすることで秘密鍵を利用して git push が実行されます。

chmod 600 /path/to/id_git_rsa
chmod 755 /path/to/git_ssh.sh

crontab -eを実行して以下のコマンドを書き込みます。

crontab
0 20 * * * cd /path/to/git_repository; export GIT_SSH=/path/to/git_ssh.sh; git add .; git commit -m "daily commit"; git push -u origin master;

これで毎日20時0分にgit pushが実行されます。

実行されない場合

crontabが実行されてないとmailにエラーが届きます。

ターミナルでmailと打つの内容が見れます。

私は以下のようなエラーが出ました。

fatal: could not read Username for 'https://github.com': Device not configured

リポジトリのリモートURLがHTTPSになっていたのが問題っぽいです。
このコマンドを打ちましょう。

git remote set-url origin git@github.com:username/repo.git

私はこれでエラーが解決でき、無事にgit pushできました。

まとめ

crontabを利用してgit pushを自動化しました。皆さんも是非crontabを利用してみてください。

参考文献

https://qiita.com/ryusukefuda/items/878556158d8f1d3d887a
https://mac-ra.com/catalina-crontab/
http://tm.root-n.com/unix:command:git:cron_git_push
http://nyangryy.hatenablog.com/entry/2013/11/12/175408

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2