我希望能够在我的脚本中接受强制和可选标志.这是我到目前为止.
#!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
非常感谢大家.到目前为止这完美无瑕.