是否可以混合使用选项(带有getopts(和参数($1....$10(?
getopt
(单数(可以处理混合的选项和参数,以及短-s
和长--long
选项和--
到结束的选项处理。
请参阅此处file1
和file2
如何与选项混合,并将它们分开:
$ args=(-ab opt file1 -c opt file2)
$ getopt -o ab:c: -- "${args[@]}"
-a -b 'opt' -c 'opt' -- 'file1' 'file2'
典型用法如下所示:
#!/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