Skip to content

Instantly share code, notes, and snippets.

@shinkou
Last active May 1, 2024 12:30
Show Gist options
  • Save shinkou/dfdc23b2b3f3af0a08c9fd58f97461f9 to your computer and use it in GitHub Desktop.
Save shinkou/dfdc23b2b3f3af0a08c9fd58f97461f9 to your computer and use it in GitHub Desktop.
A snippet to showcase how to manipulate options and arguments in Bash
#!/bin/bash
main()
{
local opt_a=
local opt_b=
local opt_c=
local args=
getargs "$@"
if [ -n "$opt_a" ]; then echo "opt_a [$opt_a]"; fi
if [ -n "$opt_b" ]; then echo "opt_b [$opt_b]"; fi
if [ -n "$opt_c" ]; then echo "opt_c [$opt_c]"; fi
for arg in "${args[@]}"; do echo "arg [$arg]"; done
}
getargs()
{
while getopts 'a:b:c:h' o; do
case $o in
a) opt_a=$OPTARG;;
b) opt_b=$OPTARG;;
c) opt_c=$OPTARG;;
h) usage; exit 0;;
*) usage; exit 1;;
esac
done
shift $((OPTIND - 1))
args=("$@")
}
usage()
{
local cmd=${0##*/}
cat <<EOF
Usage:
$cmd [ OPTION [ OPTION ... ] ]
Option:
-a ARG parameter a
-b ARG parameter b
-c ARG parameter c
-h show this help message and exit
EOF
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment