Skip to content

Instantly share code, notes, and snippets.

@taviso
Last active Dec 17, 2019
Embed
What would you like to do?
Using ctypes.sh to parse options
#!/bin/bash
#
# $ bash test.sh --my_opt=foo --my_opt bar
# option_index was int:0
# foo
# option_index was int:0
# bar
if ! source ctypes.sh; then
echo please install ctypes.sh
exit 1;
fi
struct option opts
declare -a argv=(string:${0} ${*/#/string:})
declare -a index=(int)
dlcall -r pointer -n option_index calloc 1 $(sizeof int)
dlcall -r pointer -n optptr calloc 2 $(sizeof option)
dlcall -r pointer -n argptr calloc ${#argv[@]} $(sizeof pointer)
opts[name]="string:my_opt"
opts[has_arg]="int:1"
pack $argptr argv
pack $optptr opts
while true; do
dlcall -r int -n c getopt_long ${#argv[@]} $argptr "" $optptr $option_index
dlsym -n optarg -d pointer optarg
case $c in
int:0) unpack $option_index index
echo option_index was $index
if test $optarg != $NULL; then
dlcall puts $optarg
fi
;;
int:-1) break
;;
esac
done
dlcall free $optptr
dlcall free $argptr
dlcall free $option_index
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment