Setting up an SSH key and adding it to your GitHub account is a great way to securely connect to GitHub without needing to enter your username and password every time. Here's a step-by-step guide:
Step 1: Check for Existing SSH Keys
Before generating a new SSH key, check if you already have one:
- Open a terminal (on macOS/Linux) or Git Bash (on Windows).
- Run the following command to check for existing SSH keys:
ls -al ~/.ssh
Look for files like id_rsa.pub
, id_ecdsa.pub
, or id_ed25519.pub
. These are your public SSH keys.
If you don't have any, proceed to the next step.
Step 2: Generate a New SSH Key
- Run the following command to generate a new SSH key:
ssh-keygen -t ed25519 -C "your_email@example.com"
Replace your_email@example.com
with your GitHub email address.
If you're using an older system that doesn't support ed25519
, use:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
When prompted to "Enter a file in which to save the key," press
Enter
to accept the default location.You'll be asked to enter a passphrase. This is optional but recommended for added security.
Step 3: Add the SSH Key to the SSH Agent
- Start the SSH agent in the background:
eval "$(ssh-agent -s)"
- Add your SSH private key to the SSH agent:
ssh-add ~/.ssh/id_ed25519
If you used a different name for your key, replace id_ed25519
with the correct filename.
Step 4: Copy the SSH Key to Your Clipboard
- Display your SSH public key:
cat ~/.ssh/id_ed25519.pub
If you used a different name for your key, replace id_ed25519.pub
with the correct filename.
- Copy the output to your clipboard. On macOS, you can use:
pbcopy < ~/.ssh/id_ed25519.pub
On Linux, use:
xclip -selection clipboard < ~/.ssh/id_ed25519.pub
On Windows (Git Bash), use:
clip < ~/.ssh/id_ed25519.pub
Step 5: Add the SSH Key to Your GitHub Account
- Go to GitHub and log in to your account.
- Click on your profile picture in the top-right corner and select Settings.
- In the left sidebar, click SSH and GPG keys.
- Click the New SSH key button.
- Give your key a title (e.g., "My Laptop").
- Paste the SSH key you copied earlier into the "Key" field.
- Click Add SSH key.
Step 6: Test Your SSH Connection
- Run the following command to test your SSH connection to GitHub:
ssh -T git@github.com
- If everything is set up correctly, you'll see a message like:
Hi username! You've successfully authenticated, but GitHub does not provide shell access.
Step 7: Use SSH for Git Operations
Now, when you clone a repository, use the SSH URL instead of HTTPS. For example:
git clone git@github.com:username/repository.git
For existing repositories, you can update the remote URL to use SSH:
git remote set-url origin git@github.com:username/repository.git
That's it! You've successfully set up an SSH key and added it to your GitHub account. 🎉