getopts
noun
say it: “GET-opts” /ˈɡɛtˌɑpts/
A command built into bash that reads a script's one-letter options one at a time, in any order, with their values.
What does getopts do in bash?
getopts reads a script's one-letter options, so -q -c dinner, -c dinner -q and -qc dinner all work. In ":c:q", a colon after a letter means it takes a value, which lands in $OPTARG; the colon at the start lets the script word its own errors. It doesn't read long options such as --help.
while getopts ":c:q" opt; do
case "$opt" in
c) only="$OPTARG" ;;
q) quick=yes ;;
esac
done
# ./recipes -qc breakfast sets only=breakfast quick=yes
In a sentence
- “getopts puts the value after -c in OPTARG.”
- “With getopts, -qc breakfast and -c breakfast -q both list the quick breakfasts.”
Level: Journeyman · More Unix terms at this level
Updated