Reputation: 1
Is it possible to mix options (with getopts) and arguments ($1....$10)?
Upvotes: 0
Views: 66
Reputation: 361605
getopt
(singular) can handle options and arguments intermixed, as well as short -s
and long --long
options and --
to end options processing.
See here how file1
and file2
are mixed with options and it separates them out:
$ args=(-ab opt file1 -c opt file2)
$ getopt -o ab:c: -- "${args[@]}"
-a -b 'opt' -c 'opt' -- 'file1' 'file2'
Typical usage looks like:
#!/bin/bash
options=$(getopt -o ab:c: -l alpha,bravo:,charlie: -- "$@") || exit
eval set -- "$options"
# Option variables.
alpha=0
bravo=
charlie=
# Parse each option until we hit `--`, which signals the end of options.
# Don't actually do anything yet; just save their values and check for errors.
while [[ $1 != -- ]]; do
case $1 in
-a|--alpha) alpha=1; shift 1;;
-b|--bravo) bravo=$2; shift 2;;
-c|--charlie) charlie=$2; shift 2;;
*) echo "bad option: $1" >&2; exit 1;;
esac
done
# Discard `--`.
shift
# Here's where you'd actually execute the options.
echo "alpha: $alpha"
echo "bravo: $bravo"
echo "charlie: $charlie"
# File names are available as $1, $2, etc., or in the "$@" array.
for file in "$@"; do
echo "file: $file"
done
Upvotes: 1