Last active
May 6, 2019 16:17
-
-
Save gipert/4bddc609431db2bb8ebf9e0a82ffc5f1 to your computer and use it in GitHub Desktop.
Simple getopt example for bash
This file contains 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
#include <getopt.h> | |
#include <iostream> | |
#include <string> | |
#include <vector> | |
int main(int argc, char** argv) { | |
std::string progname(argv[0]); | |
auto usage = [&]() { | |
std::cerr << "USAGE: " << progname << " [-v|--verbose] [-h|--help] [--p0 <val> (default 0.01)] file1 file2 ...\n"; | |
}; | |
const char* const short_opts = ":vh"; | |
const option long_opts[] = { | |
{ "p0", required_argument, nullptr, 1 }, | |
{ "verbose", no_argument, nullptr, 'v' }, | |
{ "help", no_argument, nullptr, 'h' }, | |
{ nullptr, no_argument, nullptr, 0 } | |
}; | |
// default p0 value | |
double p0 = 0.01; | |
int opt = 0; | |
while ((opt = getopt_long(argc, argv, short_opts, long_opts, nullptr)) != -1) { | |
switch (opt) { | |
case 1: | |
p0 = std::stod(optarg); | |
case 'v': | |
level = debug; | |
break; | |
case 'h': // -h or --help | |
case '?': // Unrecognized option | |
default: | |
usage(); | |
return 1; | |
} | |
} | |
// extra arguments | |
std::vector<std::string> args; | |
for(; optind < argc; optind++){ | |
args.emplace_back(argv[optind]); | |
} | |
if (args.empty()) {usage(); return 1;} | |
return 0; | |
} |
This file contains 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
#!/usr/bin/env bash | |
usage() { echo "USAGE: `basename $0` [-v] --config file.json --destdir /path/to/gerda-pdfs -- dir_with_raw" 1>&2; exit 1;} | |
options='vh' | |
longoptions='config:,destdir:' | |
parsed=$(getopt --name `basename $0` --options $options --longoptions $longoptions -- "$@") | |
[ $? -eq 0 ] || exit 1 | |
eval set -- "$parsed" | |
while true; do | |
case "$1" in | |
-v) | |
set -xv | |
shift | |
;; | |
--config) | |
config=$2 | |
shift 2 | |
;; | |
--destdir) | |
destdir=$2 | |
shift 2 | |
;; | |
--) | |
shift | |
break | |
;; | |
-h | *) | |
usage | |
;; | |
esac | |
done | |
# get args after all options | |
argument=$1 | |
# check mandatory options/arguments | |
[ -z "$config" ] && usage | |
[ -z "$destdir" ] && usage |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment