Last active
February 19, 2026 10:11
-
-
Save mrishu/3318b1e2148bf2efc3686b65966e42fb to your computer and use it in GitHub Desktop.
Load SSH Key from Bitwarden directly into ssh-agent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # bw-ssh-add.sh | |
| # Load an SSH key stored in Bitwarden into ssh-agent | |
| # Must be sourced so BW_SESSION persists. | |
| # Add this in ~/.zshrc or ~/.bashrc: | |
| # bw-ssh-add() { | |
| # source ~/bin/bw-ssh-add.sh "$@" | |
| # } | |
| # Prevent execution (must be sourced) | |
| if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then | |
| echo "This script must be sourced:" | |
| echo " source bw-ssh-add.sh [item name]" | |
| return 1 2>/dev/null || exit 1 | |
| fi | |
| ITEM_NAME="${1:-Bitwarden SSH Key}" | |
| # Check dependencies | |
| if ! command -v bw >/dev/null 2>&1; then | |
| echo "Error: bitwarden-cli (bw) not installed." | |
| return 1 | |
| fi | |
| if ! command -v jq >/dev/null 2>&1; then | |
| echo "Error: jq not installed." | |
| return 1 | |
| fi | |
| STATUS_JSON=$(bw status 2>/dev/null) || { | |
| echo "Error: Unable to contact Bitwarden CLI." | |
| return 1 | |
| } | |
| STATUS=$(echo "$STATUS_JSON" | jq -r '.status') | |
| case "$STATUS" in | |
| unauthenticated) | |
| echo "Not logged in. Logging in..." | |
| bw login || return 1 | |
| echo "Unlocking vault..." | |
| export BW_SESSION=$(bw unlock --raw) || return 1 | |
| ;; | |
| locked) | |
| echo "Vault locked. Unlocking..." | |
| export BW_SESSION=$(bw unlock --raw) || return 1 | |
| ;; | |
| unlocked) # Do nothing. BW_SESSION already exists | |
| ;; | |
| *) | |
| echo "Unknown Bitwarden status: $STATUS" | |
| return 1 | |
| ;; | |
| esac | |
| echo "Fetching SSH key '$ITEM_NAME'..." | |
| ITEM_NAME="Bitwarden SSH Key" | |
| PRIVATE_KEY=$(bw get item "$ITEM_NAME" --session "$BW_SESSION" | jq -r '.sshKey.privateKey') | |
| if [[ -z "$PRIVATE_KEY" || "$PRIVATE_KEY" == "null" ]]; then | |
| echo "Failed to retrieve private key." | |
| return 1 | |
| fi | |
| echo "$PRIVATE_KEY" | ssh-add - >/dev/null | |
| if [[ $? -eq 0 ]]; then | |
| echo "SSH key loaded into ssh-agent." | |
| else | |
| echo "Failed to load SSH key into ssh-agent." | |
| return 1 | |
| fi |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
bitwarden-cliandjq(these are the name of the package in Arch Linux).ssh-agentshould also be running.