Last active
November 10, 2024 19:55
-
-
Save drmalex07/6bcd65a0861f58b646a0 to your computer and use it in GitHub Desktop.
A small example on Bash getopts. #bash #getopt #getopts
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
#!/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 |
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
#!/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: <${@}>" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This:
${@}
is useful as hell! Thanks for sharing 😄