LoginSignup
144

More than 5 years have passed since last update.

Git における SSH オプション指定方法あれこれ

Last updated at Posted at 2012-06-10

このエントリーはGitアドベントカレンダーの十日目です。九日目は KitaitiMakoto さんの「ファイルの変更を監視するプログラムと仲良くする」でした。ローカルリポジトリとフックスクリプトの組み合わせはあまり見かけませんが、いろいろ応用できそうですね。

SSH Protocol URL

さて、 Git でリモートリポジトリを扱うとき、もっとも馴染み深いのは以下のような URL でしょう。

git@github.com:kyanny/hello.git

これは SSH Protocol の URL なので、以下のようにも表現できます。

ssh://git@github.com:22/kyanny/hello.git

SSH Protocol の URL では、リモートホストのユーザー名、ホスト名、 SSH のポート番号、そしてリポジトリのパスを指定できます。

ssh_config

その他の SSH オプションを指定したい場合は ~/.ssh/config を利用します。GitHub へのアクセス時に、 ~/.ssh/id_rsa~/.ssh/id_dsa ではなく特定の秘密鍵ファイルを使いたい場合は以下のように設定します。

~/.ssh/config
Host github.com
    IdentityFile ~/.ssh/github_id_rsa

~/.ssh/config を利用する場合は、ファイルのパーミッションを 0600 に変更する必要があります

環境変数 GIT_SSH

~/.ssh/config は大変便利ですが、 Git とは無関係の SSH 接続時にも参照されるので不都合なこともあります。別の方法として、 GIT_SSH 環境変数に SSH のラッパースクリプトを指定することができます。

git-ssh.sh
#!/bin/sh
exec ssh -oIdentityFile=~/.ssh/github_id_rsa "$@"
$ GIT_SSH=git-ssh.sh git push git@github.com:kyanny/hello.git master

リモートホストに SSH 接続する場合と Git アクセスする場合で、それぞれ別の接続情報を使い分けたいときなどに便利です。必要に応じて ~/.bashrc~/.zshrc などにエイリアスを定義するのもよいでしょう。

alias git="GIT_SSH=git-ssh.sh git"

参考 URL

  • git-push(1) - GIT URLS の項に SSH Protocol の詳細が載っています
  • git(1) - GIT_SSH は other の項で解説されています

明日は tyabe さんです。

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
144