How to Use SSH with Git: Simple Setup and Usage Guide
To use
ssh with git, generate an SSH key pair with ssh-keygen, add the public key to your Git hosting service, and clone or push repositories using the SSH URL. This allows secure, password-less authentication when interacting with Git remotes.Syntax
Using SSH with Git involves these main commands:
ssh-keygen: Creates a new SSH key pair.ssh-add: Adds your private key to the SSH agent for authentication.git clone git@host:user/repo.git: Clones a repository using SSH.git remote add origin git@host:user/repo.git: Adds a remote repository via SSH.
The SSH URL format is git@host:user/repo.git, where host is your Git server (like github.com).
bash
ssh-keygen -t ed25519 -C "your_email@example.com"
ssh-add ~/.ssh/id_ed25519
git clone git@github.com:user/repo.gitExample
This example shows how to generate an SSH key, add it to the SSH agent, and clone a GitHub repository using SSH.
bash
ssh-keygen -t ed25519 -C "your_email@example.com"
# Press Enter to accept defaults and optionally set a passphrase
ssh-add ~/.ssh/id_ed25519
git clone git@github.com:octocat/Hello-World.gitOutput
Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/user/.ssh/id_ed25519):
Your identification has been saved in /home/user/.ssh/id_ed25519
Your public key has been saved in /home/user/.ssh/id_ed25519.pub
Identity added: /home/user/.ssh/id_ed25519 (your_email@example.com)
Cloning into 'Hello-World'...
remote: Enumerating objects: 10, done.
remote: Counting objects: 100% (10/10), done.
remote: Compressing objects: 100% (8/8), done.
Receiving objects: 100% (10/10), done.
Common Pitfalls
Common mistakes when using SSH with Git include:
- Not adding the SSH key to your Git hosting account (like GitHub or GitLab).
- Using the HTTPS URL instead of the SSH URL for cloning or pushing.
- Not starting the SSH agent or adding the private key with
ssh-add. - File permission issues on SSH keys (private key should be readable only by you).
Example of wrong and right remote URL:
bash
git remote set-url origin https://github.com/user/repo.git # Wrong for SSH usage
git remote set-url origin git@github.com:user/repo.git # Correct SSH URLQuick Reference
| Command | Purpose |
|---|---|
| ssh-keygen -t ed25519 -C "email@example.com" | Generate SSH key pair |
| ssh-add ~/.ssh/id_ed25519 | Add private key to SSH agent |
| git clone git@host:user/repo.git | Clone repo using SSH |
| git remote set-url origin git@host:user/repo.git | Set remote URL to SSH |
| chmod 600 ~/.ssh/id_ed25519 | Secure private key permissions |
Key Takeaways
Generate an SSH key pair and add the public key to your Git hosting account.
Use the SSH URL format (git@host:user/repo.git) to clone or push repositories.
Add your private key to the SSH agent with ssh-add for smooth authentication.
Ensure your private key file permissions are secure (chmod 600).
Avoid mixing HTTPS and SSH URLs to prevent authentication errors.