Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@taviso
Last active December 17, 2019 02:42
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 taviso/e21aaf189f72b356e1a7f2e7f3d03a2a to your computer and use it in GitHub Desktop.
Save taviso/e21aaf189f72b356e1a7f2e7f3d03a2a to your computer and use it in GitHub Desktop.
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