我希望能够在我的脚本中同时接受强制性和可选性标志。这是我到目前为止的内容。
#!bin/bash
while getopts ":a:b:cdef" opt; do
case $opt in
a ) APPLE="$OPTARG";;
b ) BANANA="$OPTARG";;
c ) CHERRY="$OPTARG";;
d ) DFRUIT="$OPTARG";;
e ) EGGPLANT="$OPTARG";;
f ) FIG="$OPTARG";;
\?) echo "Invalid option: -"$OPTARG"" >&2
exit 1;;
: ) echo "Option -"$OPTARG" requires an argument." >&2
exit 1;;
esac
done
echo "Apple is "$APPLE""
echo "Banana is "$BANANA""
echo "Cherry is "$CHERRY""
echo "Dfruit is "$DFRUIT""
echo "Eggplant is "$EGGPLANT""
echo "Fig is "$FIG""
但是,以下内容的输出:
bash script.sh -a apple -b banana -c cherry -d dfruit -e eggplant -f fig
...输出此:
Apple is apple
Banana is banana
Cherry is
Dfruit is
Eggplant is
Fig is
如您所见,可选标志不会像使用必需标志那样使用$ OPTARG提取参数。有没有一种方法可以读取可选标志上的$ OPTARG而不摆脱整洁的“ :)”错误处理?
编辑:我遵循下面吉尔伯特的建议。这是我所做的:
#!/bin/bash if [[ "$1" =~ ^((-{1,2})([Hh]$|[Hh][Ee][Ll][Pp])|)$ ]]; then print_usage; exit 1 else while [[ $# -gt 0 ]]; do opt="$1" shift; current_arg="$1" if [[ "$current_arg" =~ ^-{1,2}.* ]]; then echo "WARNING: You may have left an argument blank. Double check your command." fi case "$opt" in "-a"|"--apple" ) APPLE="$1"; shift;; "-b"|"--banana" ) BANANA="$1"; shift;; "-c"|"--cherry" ) CHERRY="$1"; shift;; "-d"|"--dfruit" ) DFRUIT="$1"; shift;; "-e"|"--eggplant" ) EGGPLANT="$1"; shift;; "-f"|"--fig" ) FIG="$1"; shift;; * ) echo "ERROR: Invalid option: \""$opt"\"" >&2 exit 1;; esac done fi if [[ "$APPLE" == "" || "$BANANA" == "" ]]; then echo "ERROR: Options -a and -b require arguments." >&2 exit 1 fi
非常感谢大家。到目前为止,这一切正常。
我希望能够在我的脚本中同时接受强制性和可选性标志。到目前为止,这就是我所拥有的。 #!bin / bash而getopts“:a:b:cdef” opt;是否在$)APPLE =“ $ OPTARG”中使用$ opt; ...
大多数shell getopts困扰我很长时间了,包括缺乏对可选参数的支持。
:
的意思是“接受论点”,而不是“强制论点”。也就是说,不带:
的选项字符表示标志样式的选项(无参数),而带:
的选项字符表示带有参数的选项。
这并不容易...只要getopts
知道,实际上就必须需要任何“可选”选项参数。当然,一个可选参数必须与该选项一起成为脚本相同参数的一部分。否则,带有可选参数的选项-f
和带有必需参数的选项-a
可能会引起混淆:
对于bash,这是我最喜欢的解析/支持cli参数的方法。我使用了getopts,令人沮丧的是它不支持长选项。我喜欢它的其他工作方式-特别是对于内置功能。
bash
的getopts