Skip to content

Instantly share code, notes, and snippets.

@caruccio
Last active November 17, 2023 13:07
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 caruccio/753c8c46faaf34a91962d47e47279cf8 to your computer and use it in GitHub Desktop.
Save caruccio/753c8c46faaf34a91962d47e47279cf8 to your computer and use it in GitHub Desktop.
Shell long-options
#!/bin/bash
SERVER=''
SHORT_PARAM='-s' # short option name
LONG_PARAM='--server' # long option name
while [ $# -gt 0 ]; do
case "${1}" in
$SHORT_PARAM=*|$SHORT_PARAM*|$LONG_PARAM=*|$LONG_PARAM) ## matches both`[-s|--server]=value` and `[-s|--server] value`
param="${1#$SHORT_PARAM}" ## removes `-s` from the front of $1
param="${param#$LONG_PARAM}" ## removes `--server` from the front of $1
if [ "${param:0:1}" == = ]; then ## if there is a `=` as the first char
param=${param:1} ## removes `=`. this acts like an slice (goland) and list range (python)
## the value is the rest of $1, after the `=`
elif [ -z "${param:0:1}" ]; then
shift ## otherwise, the value is the next parameter ($2). `shift` "eats" $1
param=$1 ## and the new `$1` is nown the former `$2`.
fi
SERVER="$param" ## save the value for future use
;;
*) echo Invalid parameter: $1
esac
shift
done
echo SERVER=$SERVER
# Tests:
# $ for i in -sbastion -s=bastion '-s bastion' --server=bastion '--server bastion'; do
# /tmp/params.sh $i
# done
# SERVER=bastion
# SERVER=bastion
# SERVER=bastion
# SERVER=bastion
# SERVER=bastion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment