Skip to content

Instantly share code, notes, and snippets.

@kobymeir
Created March 4, 2026 06:17
Show Gist options
  • Select an option

  • Save kobymeir/ae3d7ad92b035bd74b5914577a3cd128 to your computer and use it in GitHub Desktop.

Select an option

Save kobymeir/ae3d7ad92b035bd74b5914577a3cd128 to your computer and use it in GitHub Desktop.
./generate_ssh_key.sh -c "John Doe <john.doe@example.com>"

Usage:

./generate_ssh_key.sh -c "John Doe <john.doe@example.com>"
#!/usr/bin/env bash
set -euo pipefail
SSH_DIR="${HOME}/.ssh"
KEY_FILE="${SSH_DIR}/id_rsa"
usage() {
cat <<EOF
Usage:
$(basename "$0") -c <comment>
Description:
Generate a non-interactive ed25519 SSH key with no passphrase.
Existing keys will be backed up.
Options:
-c, --comment Comment to embed in the public key
-h, --help Show this help message
Example:
$(basename "$0") -c "John Doe <john.doe@example.com>"
EOF
}
COMMENT=""
while [[ $# -gt 0 ]]; do
case "$1" in
-c|--comment)
COMMENT="$2"
shift 2
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown argument: $1"
echo
usage
exit 1
;;
esac
done
if [[ -z "${COMMENT}" ]]; then
echo "Error: comment is required"
echo
usage
exit 1
fi
mkdir -p "${SSH_DIR}"
chmod 700 "${SSH_DIR}"
BACKUP_SUFFIX="$(date +%Y%m%d_%H%M%S)"
if [[ -f "${KEY_FILE}" ]]; then
mv "${KEY_FILE}" "${KEY_FILE}.${BACKUP_SUFFIX}.bak"
fi
if [[ -f "${KEY_FILE}.pub" ]]; then
mv "${KEY_FILE}.pub" "${KEY_FILE}.pub.${BACKUP_SUFFIX}.bak"
fi
ssh-keygen \
-t ed25519 \
-C "${COMMENT}" \
-f "${KEY_FILE}" \
-N "" \
-q
chmod 600 "${KEY_FILE}"
chmod 644 "${KEY_FILE}.pub"
echo "SSH key generated successfully:"
echo "Private key: ${KEY_FILE}"
echo "Public key : ${KEY_FILE}.pub"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment