Last active
December 17, 2021 23:40
-
-
Save alexcreek/f28c037beb3349f220e144c747d1e37b to your computer and use it in GitHub Desktop.
How to use getopts in 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
#!/bin/bash | |
usage() { | |
echo "Usage: $(basename "$0") [-v] [-f filename] [-g group] positional-param" | |
exit 1 | |
} | |
if [[ "$#" -lt 1 ]]; then | |
usage | |
fi | |
# Prefix getops string with : to silence errors | |
# Option without : is just an option (-v) | |
# Append : to an option to accept a parameter (-f filename) | |
while getopts ":vf:g:" opt; do | |
case $opt in | |
v) echo "-v enabled";; | |
f) echo "-f was passed $OPTARG";; | |
g) echo "-g was passed $OPTARG";; | |
?) case $OPTARG in | |
f|g) echo "-$OPTARG missing argument"; usage;; | |
?) usage;; | |
esac | |
esac | |
done | |
# Remove all params processed by getopts so we can use $1 like normal | |
shift $((OPTIND - 1)) | |
echo "positional parameter passed is $1" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment