Specify Git identity based on SSH host or identity

2019-08-20 07:11发布

问题:

Git is hassling me with the usual

*** Please tell me who you are.
Run
  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"
to set your account's default identity.
Omit --global to set the identity only in this repository.

to which I usually respond with

git config user.email "me@example.com"
git config user.name "Me Name"

I don't wish to set the above globally as I have multiple hosts and wish to use a different Git identity for each SSH host. Is it possible to link the Git identities to the SSH hosts and/or identities, e.g. by having some sort of common config file

Host github.com
    IdentityFile ~/.ssh/github_rsa
    user.email "me@example.com"
    user.name "Me Name"
Host gitlab.com
    IdentityFile ~/.ssh/gitlab_rsa
    user.email "another@example.com"
    user.name "Another Name"

回答1:

I don't see a generic way for this but there could be a custom solution like this:

Create a properties file with the Name of the host for each git Server that stores the user Settings:

echo 'user.email "me@example.com"' > $HOME/.mygitconfig/github.com.user
echo 'user.name "Me Name"' >> $HOME/.mygitconfig/github.com.user

and create a script to clone an repository along this lines (untested):

cat %HOME/bin/clonerepo

#!/user/bin/bash
git clone  git@$1/$2 .
while IFS=$'\n' read -r user_data; do
   git config $(user_data)
done < $(HOME)/.mygitconfig/$1.user

You use it:

 $HOME/bin/clonerepo github.com path/to/repo.git