Skip to content

Instantly share code, notes, and snippets.

@Morozov-5F
Created November 13, 2017 10:50
Show Gist options
  • Save Morozov-5F/b747526ea29b63f4b3e465821cc81853 to your computer and use it in GitHub Desktop.
Save Morozov-5F/b747526ea29b63f4b3e465821cc81853 to your computer and use it in GitHub Desktop.
Last problem
#!/bin/bash
# String with available options (more info: man getopt)
# Colon after argument means that value is required for this argumen
# h -- help
# a -- main args
OPTSTRING="ha:"
VALUE=""
do_work()
{
local arg="$1"
# Do whatever you want
echo "Test: $arg"
exit 1;
}
print_usage()
{
echo "USAGE: $0 [ options ]"
echo "OPTIONS:"
echo " -h Print this message and exit"
echo " -a <val> Option description"
exit "$1"
}
process_options()
{
local options_provided="false"
# Check that we have some arguments
if [[ -z "$@" ]]; then
echo "No options provided!"
print_usage 1
fi
# Parse incoming options
while getopts "$OPTSTRING" opt; do
shift $((OPTIND-1))
case $opt in
# Usage flag
h)
print_usage 0
;;
# Main value flag
a)
VALUE=$OPTARG
;;
# Option used without required argument
:)
print_usage 1
;;
# Invalid options (optarg manually prints error message)
*)
print_usage 1
;;
esac
done
# Check for extra arguments
if [[ -n "$@" ]]; then
echo "Too many arguments!"
print_usage 1
fi
}
# Process incoming options
process_options "$@"
# Do some wotk
do_work "$VALUE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment