Last active
August 12, 2019 17:04
-
-
Save leighklotz/b0334f2e1a39ad0537cc1e6027969ae5 to your computer and use it in GitHub Desktop.
print or match Host and Hostname aliases from ~/.ssh/config
This file contains hidden or 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
| #!/bin/bash | |
| function usage() { | |
| echo "usage:" | |
| name=`basename $0` | |
| echo "$name: print Host and Hostname aliases from ~/.ssh/config" | |
| echo "$name foo: grep for foo in above output" | |
| echo "$name -e|--exact foo: grep for '^foo ' in above output and print only hostname. example: ping \$(sshaliases --exact foo)" | |
| echo "$name -h|--help: this help" | |
| } | |
| EXACT="" | |
| MATCH=() | |
| for i in "$@" | |
| do | |
| case $i in | |
| -e|--exact) | |
| EXACT="YES" | |
| shift | |
| ;; | |
| -h|--help) | |
| usage | |
| exit | |
| ;; | |
| *) | |
| MATCH+=("$1") # save it in an array for later | |
| shift | |
| ;; | |
| esac | |
| done | |
| function maybe_cut() { | |
| if [ "$EXACT" == "YES" ] ; then | |
| cut -d' ' -f2 | |
| else | |
| cat | |
| fi | |
| } | |
| function maybe_grep() { | |
| if [ "$MATCH" == "" ] ; then | |
| cat | |
| elif [ "$EXACT" == "YES" ] ; then | |
| grep "^${MATCH} " | |
| else | |
| grep "${MATCH}" | |
| fi | |
| } | |
| awk ' | |
| /^Host / { | |
| gsub("^Host ", "", $0); | |
| printf "%s ", $0; | |
| } | |
| /^[ \t]+Hostname / { | |
| gsub("^[ \t]*Hostname[ \t]+", "", $0); | |
| print; | |
| } | |
| ' < ~/.ssh/config | sort | maybe_grep | maybe_cut |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment