【发布时间】:2019-07-24 11:40:28
【问题描述】:
是否可以混合使用选项(使用 getopts)和参数($1....$10)?
【问题讨论】:
-
在 bash 中解析 cla stackoverflow.com/questions/192249/…
是否可以混合使用选项(使用 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
【讨论】: