Skip to content

Instantly share code, notes, and snippets.

@drmalex07
Last active May 3, 2024 03:03
Show Gist options
  • Save drmalex07/6bcd65a0861f58b646a0 to your computer and use it in GitHub Desktop.
Save drmalex07/6bcd65a0861f58b646a0 to your computer and use it in GitHub Desktop.
A small example on Bash getopts. #bash #getopt #getopts
#!/bin/bash
#
# Example using getopt (vs builtin getopts) that can also handle long options.
# Another clean example can be found at:
# http://www.bahmanm.com/blogs/command-line-options-how-to-parse-in-bash-using-getopt
#
aflag=n
bflag=n
cargument=
# Parse options. Note that options may be followed by one colon to indicate
# they have a required argument
if ! options=$(getopt -o abc: -l along,blong,clong: -- "$@")
then
# Error, getopt will put out a message for us
exit 1
fi
set -- $options
while [ $# -gt 0 ]
do
# Consume next (1st) argument
case $1 in
-a|--along)
aflag="y" ;;
-b|--blong)
bflag="y" ;;
# Options with required arguments, an additional shift is required
-c|--clong)
cargument="$2" ; shift;;
(--)
shift; break;;
(-*)
echo "$0: error - unrecognized option $1" 1>&2; exit 1;;
(*)
break;;
esac
# Fetch next argument as 1st
shift
done
#!/bin/bash
while getopts ":da:" opt; do
case $opt in
d)
echo "Entering DEBUG mode"
;;
a)
echo "Got option 'a' with argurment ${OPTARG}"
;;
:)
echo "Error: option ${OPTARG} requires an argument"
;;
?)
echo "Invalid option: ${OPTARG}"
;;
esac
done
shift $((OPTIND-1))
echo "Remaining args are: <${@}>"
@jimmyadaro
Copy link

This: ${@} is useful as hell! Thanks for sharing 😄

@dmotte
Copy link

dmotte commented Nov 13, 2023

Very useful! 😄 Thank you so much

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment