Skip to content

Instantly share code, notes, and snippets.

@bitdivine
Created August 21, 2014 10:25
Show Gist options
  • Save bitdivine/08763ed457dd04481f59 to your computer and use it in GitHub Desktop.
Save bitdivine/08763ed457dd04481f59 to your computer and use it in GitHub Desktop.
shell script to parse user@host:port into its constituent parts, with defaults.
# Parse user@host:port into its constituent parts, with defaults.
# Explode if there are errors:
set -eu
# The parser with defaults:
parse() {
target="$1"
hostport="${1#*@}"
host="${hostport%:*}"
port="${hostport#${host}}"
port="${port#:}"
user="${target%$hostport}"
user="${user%@}"
echo "${user:-lala}" "${host:-dipsy}" "${port:-60}"
}
# Tests:
parsed() {
printf "% -30s parsed is " "$1"
set $(parse "$1")
printf "'${1:-}' '${2:-}' '${3:-}'\n"
}
parsed "root@dangermouse.com:50"
parsed "dangermouse.com:50"
parsed "root@dangermouse.com"
parsed "dangermouse.com"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment