Skip to content

Instantly share code, notes, and snippets.

@octocat
Created July 3, 2014 19:33
Show Gist options
  • Save octocat/2a6851cde24cdaf4b85b to your computer and use it in GitHub Desktop.
Save octocat/2a6851cde24cdaf4b85b to your computer and use it in GitHub Desktop.

Revisions

  1. octocat created this gist Jul 3, 2014.
    52 changes: 52 additions & 0 deletions ssh_key_add.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    # Note: ~/.ssh/environment should not be used, as it
    # already has a different purpose in SSH.

    env=~/.ssh/agent.env

    # Note: Don't bother checking SSH_AGENT_PID. It's not used
    # by SSH itself, and it might even be incorrect
    # (for example, when using agent-forwarding over SSH).

    agent_is_running() {
    if [ "$SSH_AUTH_SOCK" ]; then
    # ssh-add returns:
    # 0 = agent running, has keys
    # 1 = agent running, no keys
    # 2 = agent not running
    # if your keys are not stored in ~/.ssh/id_rsa.pub or ~/.ssh/id_dsa.pub, you'll need
    # to paste the proper path after ssh-add
    ssh-add -l >/dev/null 2>&1 || [ $? -eq 1 ]
    else
    false
    fi
    }

    agent_has_keys() {
    # if your keys are not stored in ~/.ssh/id_rsa.pub or ~/.ssh/id_dsa.pub, you'll need
    # to paste the proper path after ssh-add
    ssh-add -l >/dev/null 2>&1
    }

    agent_load_env() {
    . "$env" >/dev/null
    }

    agent_start() {
    (umask 077; ssh-agent >"$env")
    . "$env" >/dev/null
    }

    if ! agent_is_running; then
    agent_load_env
    fi

    # if your keys are not stored in ~/.ssh/id_rsa.pub or ~/.ssh/id_dsa.pub, you'll need
    # to paste the proper path after ssh-add
    if ! agent_is_running; then
    agent_start
    ssh-add
    elif ! agent_has_keys; then
    ssh-add
    fi

    unset env