Last active
November 1, 2015 17:25
-
-
Save radekg/fb937205923a2a57d12b to your computer and use it in GitHub Desktop.
Poor man's option parser in bash
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 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