Migrating a Git repository from HTTPS to SSH

Step 1: Verify SSH Keys

First, ensure you have SSH keys set up on your machine and added to your GitHub account.

  1. Check for existing SSH keys:
    ls -al ~/.ssh

    Look for files named id_rsa and id_rsa.pub or similar.

  2. Generate a new SSH key (if necessary):
    ssh-keygen -t rsa -b 4096 -C "[email protected]"
    

    Follow the prompts to save the key (default location is fine).

  3. Add your SSH key to the SSH agent:
    eval "$(ssh-agent -s)"
    ssh-add ~/.ssh/id_rsa
    
  4. Add the SSH key to your GitHub account: Copy the contents of your public key file to the clipboard:
    cat ~/.ssh/id_rsa.pub
    

    Then, add it to your GitHub account by going to Settings > SSH and GPG keys > New SSH key.

Step 2: Update Remote URL

  1. Navigate to your local repository:
    cd /path/to/your/repo
    
  2. Get the current remote URL:
    git remote -v
    
  3. Update the remote URL to use SSH: Replace origin with the name of your remote if it’s different.
    git remote set-url origin [email protected]:username/repo.git
    

    Replace username with your GitHub username and repo with the name of your repository.

  4. Verify the change:
    git remote -v
    

    You should see the SSH URL listed.

Step 3: Test the Connection

  1. Test the SSH connection:

    You should see a success message like “Hi username! You’ve successfully authenticated, but GitHub does not provide shell access.”

  2. Fetch from the remote to ensure everything is working:
    git fetch
    

If everything is set up correctly, your repository should now be using SSH instead of HTTPS.