Skip to content

Instantly share code, notes, and snippets.

@andkirby
Last active October 1, 2020 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andkirby/20e5b4880bdf52b22b33dab72a7a02a4 to your computer and use it in GitHub Desktop.
Save andkirby/20e5b4880bdf52b22b33dab72a7a02a4 to your computer and use it in GitHub Desktop.
Merge ssh split config files into end ~/.ssh/config.
################################################################################
# This script can merge all split SSH configuration into `~/.ssh/config` file.
#
# HOW IT WORKS
# It will merge all files by mask config.*.merge, i.e.:
# ~/.ssh/config.MY_PROJECT.merge
# Initial exists `~/.ssh/config` file will be copied to `~/.ssh/config.orig`.
# Use this `config.orig` for further changes.
#
# Anyway, you may not use this script and just run:
# $ tail -n +1 ~/.ssh/config.{orig,*.merge} > ~/.ssh/config
# It will do the same ;)
#
# -----------------------------------------
# Env variables | Default value
# -----------------------------------------
# SSH_MERGE_MASK | config.*.merge
# SSH_MERGE_HOME_DIR | ~/.ssh
################################################################################
set -o pipefail
set -o errexit
set -o nounset
#set -o xtrace
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
__file="${__dir}/$(basename "${BASH_SOURCE[0]}")"
readonly __dir __file
cd ${__dir}
ssh_dir=${SSH_MERGE_HOME_DIR:-${HOME}/.ssh}
config_mask=${SSH_MERGE_MASK:-'config.*.merge'}
# DEBUG (if xtrace is ON): Show list of found files
[[ $- =~ x ]] && ls ${ssh_dir}/${config_mask} | tr ' ' "\n"
# Copy original .ssh/config to .ssh/config.orig
# if .ssh/config.orig wasn't created before
copy_config () {
touch ${ssh_dir}/config
if [ ! -f ${ssh_dir}/config.orig ]; then
cp ${ssh_dir}/config{,.orig} && \
echo -e '\e[33m''Exists ~/.ssh/config file stored in ~/.ssh/config.orig. Please use it for further custom changes.''\e[0m'
fi
}
# Merge .ssh/config.*.merge files
merge_ssh_configs () {
cat ${ssh_dir}/config.orig > ${ssh_dir}/config
echo -e "\n\n# Merged configs from ${ssh_dir}/${config_mask}\n" >> ${ssh_dir}/config
tail -n +1 ${ssh_dir}/${config_mask} >> ${ssh_dir}/config
}
# merge configs
copy_config
merge_ssh_configs
# end
@andkirby
Copy link
Author

andkirby commented Oct 1, 2020

Quick command for the same action:

tail -n +1 ~/.ssh/config.{orig,*.merge} > ~/.ssh/config

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment