Skip to content

Instantly share code, notes, and snippets.

@kbon
Created October 1, 2015 08:32
Show Gist options
  • Save kbon/a983d34c0474e2cd5e90 to your computer and use it in GitHub Desktop.
Save kbon/a983d34c0474e2cd5e90 to your computer and use it in GitHub Desktop.
Generate ~/.ssh/config from files in ~/.ssh/config.d
#!/bin/bash
#
# Generates SSH config from elements in config.d directory
# 2013/09/24 kristiaan.bonjean@newtec.eu
#
# Returns last modification epoch seconds for given file
# Usage: GetLastModification path
GetLastModification() {
if [[ ! -f "$1" ]]; then
echo "File $1 not found: defaulting last modification time to epoch 0" >&2
echo 0
return 0
fi
if [[ $(uname -a|cut -d' ' -f1) == 'Darwin' ]]; then
# On Mac OS X
eval $(stat -s "$1")
echo $st_mtime
else
# On Linux (assuming this works)
stat -c '%Y' "$1"
fi
}
SSH_CONFIG=~/.ssh/config
SSH_CONFIGD=~/.ssh/config.d
M_CONFIG=$(GetLastModification $SSH_CONFIG)
[[ ! -d $SSH_CONFIGD ]] && mkdir -p $SSH_CONFIGD
LAST_M_ELEM=$(find $SSH_CONFIGD -type f|xargs ls -t|head -1)
if [[ "$LAST_M_ELEM" == "" ]]; then
echo "No SSH config elements found: not generating SSH config file" >&2
exit 1
fi
M_ELEM=$(GetLastModification $LAST_M_ELEM)
if [[ $M_ELEM -gt $M_CONFIG ]]; then
# A config element was found newer than SSH config
echo "Regenerating SSH config"
cat <<-HEADEREND > $SSH_CONFIG
### SSH config generated by $(basename $0) on $(date)
### Do not modify this file directly: modify elements in ${SSH_CONFIGD} and regenerate.
HEADEREND
(find $SSH_CONFIGD -type f|sort|xargs cat) >> $SSH_CONFIG
fi
echo "SSH config up-to-date."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment