Skip to content

Instantly share code, notes, and snippets.

@radekg
Last active November 1, 2015 17:25
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 radekg/fb937205923a2a57d12b to your computer and use it in GitHub Desktop.
Save radekg/fb937205923a2a57d12b to your computer and use it in GitHub Desktop.
Poor man's option parser in bash
#!/bin/bash
function opt_parse() {
local _idx=1
local _last=""
while [ $_idx -lt $# ] || [ $_idx -eq $# ]; do
_v=${!_idx}
if [[ $_v == --* ]]; then
local _name=$(echo $_v | tr - _)
eval "__program_argument${_name}=::is-arg-set"
_last=$_name
else
local e="__program_argument$_last"
if [ -z "${!e}" ] || [ "${!e}" == "::is-arg-set" ]; then
eval "__program_argument$_last=$_v"
else
eval "__program_argument$_last=${!e},$_v"
fi
fi
let _idx=_idx+1
done
}
function opt_get() {
local _name=$(echo $1 | tr - _)
local e="__program_argument$_name"
if [ "${!e}" == "::is-arg-set" ]; then
echo ""
else
echo ${!e}
fi
}
function is_opt() {
local _v=$(opt_get $1)
if [ -n "$_v" ] || [ "$_v" == "::is-arg-set" ]; then
return 0
else
return 1
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment