From 352ee6de86235da8569deda8a39831a1663673f3 Mon Sep 17 00:00:00 2001 From: Managor <42655600+Managor@users.noreply.github.com> Date: Thu, 26 Dec 2024 09:18:29 +0200 Subject: [PATCH] getopts: add page (#15237) --- pages/common/getopts.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 pages/common/getopts.md diff --git a/pages/common/getopts.md b/pages/common/getopts.md new file mode 100644 index 0000000000..4cccb600c7 --- /dev/null +++ b/pages/common/getopts.md @@ -0,0 +1,25 @@ +# getopts + +> Parse shell options from arguments. +> This command does not support longform options and thus using `getopt` is recommended instead. +> More information: . + +- Check if an option is set: + +`getopts {{x}} {{opt}}; echo $opt` + +- Set an option to require an argument and check said argument: + +`getopts {{x}}: {{opt}}; echo $OPTARG` + +- Check for multiple options: + +`while getopts {{xyz}} {{opt}}; do case $opt in x) echo x is set;; y) echo y is set;; z) echo z is set;; esac; done` + +- Set `getopts` to silent mode and handle option errors: + +`while getopts :{{x:}} {{opt}}; do case $opt in x) ;; :) echo "Argument required";; ?) echo "Invalid argument" esac;; done` + +- Reset `getopts`: + +`OPTIND=1`