Skip to content

Instantly share code, notes, and snippets.

@steelywing
Created March 3, 2026 07:59
Show Gist options
  • Select an option

  • Save steelywing/4c6855bc48814a4223e45324acf5cda0 to your computer and use it in GitHub Desktop.

Select an option

Save steelywing/4c6855bc48814a4223e45324acf5cda0 to your computer and use it in GitHub Desktop.
Add SSH public key
#!/bin/bash
# Get current user and home directory
USER=$(whoami)
HOME_DIR=$HOME
SSH_DIR="$HOME_DIR/.ssh"
AUTH_KEYS="$SSH_DIR/authorized_keys"
# Check if a key was provided
if [ -z "$1" ]; then
echo "Usage: $0 \"public_key_string\""
exit 1
fi
PUBKEY="$1"
# Create .ssh directory if it does not exist
if [ ! -d "$SSH_DIR" ]; then
mkdir -p "$SSH_DIR"
chmod 700 "$SSH_DIR"
fi
# Check if the key already exists
if grep -Fxq "$PUBKEY" "$AUTH_KEYS" 2>/dev/null; then
echo "This public key already exists in $AUTH_KEYS"
else
echo "$PUBKEY" >> "$AUTH_KEYS"
chmod 600 "$AUTH_KEYS"
echo "Public key has been added to $AUTH_KEYS"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment