Last active
November 4, 2022 20:49
strongDM bash completion of hostnames for "sdm ssh [hostname]"
This file contains 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 | |
# fetch server hostnames from `sdm status` to use as completions for `sdm ssh [hostname]` | |
# save the sdm status to a local file from a cron job to speed this up a lot: | |
# sdm status --filter 'TYPE:ssh*' | tail -n +2 | awk '{print $1}' | sort -u > /var/tmp/sdm-status | |
# h/t https://iridakos.com/programming/2018/03/01/bash-programmable-completion-tutorial | |
update_frequency=4h | |
compwords_file=/var/tmp/sdm-status | |
_sdm_ssh_completions() | |
{ | |
if [ "${#COMP_WORDS[@]}" != "3" ]; then | |
return | |
fi | |
# is this "sdm ssh" ? | |
if [ "${3}" != "ssh" ]; then | |
return | |
fi | |
# keep the suggestions in a local variable | |
# local suggestions=($(compgen -W "$(sdm status --filter 'TYPE:ssh*' | tail -n +2 | awk '{print $1}')" -- "${COMP_WORDS[2]}")) | |
# occasionally save "sdm status" output to a file for much faster completions | |
if [ ! -s "$compwords_file" ]; then | |
sdm status --filter 'TYPE:ssh*' | tail -n +2 | awk '{print $1}' > $compwords_file | |
elif ! test "$( find $compwords_file -ctime -${update_frequency} 2>/dev/null )"; then | |
# echo "Updating compwords" | |
sdm status --filter 'TYPE:ssh*' | tail -n +2 | awk '{print $1}' > $compwords_file | |
fi | |
local suggestions=($(compgen -W "$(cat /var/tmp/sdm-status)" -- "${COMP_WORDS[2]}")) | |
if [ "${#suggestions[@]}" == "1" ]; then | |
# if there's only one match, we remove the command literal | |
# to proceed with the automatic completion of the number | |
local number=$(echo ${suggestions[0]/%\ */}) | |
COMPREPLY=("$number") | |
else | |
# more than one suggestions resolved, | |
# respond with the suggestions intact | |
for i in "${!suggestions[@]}"; do | |
suggestions[$i]="$(printf '%*s' "-$COLUMNS" "${suggestions[$i]}")" | |
done | |
COMPREPLY=("${suggestions[@]}") | |
fi | |
} | |
complete -F _sdm_ssh_completions sdm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
use "sdm status" not "sdm admin list"