1. 使用空格分隔
实际用法
./myscript.sh -e conf -s /etc -l /usr/lib /etc/hosts
实现脚本
#!/bin/bashPOSITIONAL=()while [[ $# -gt 0 ]]; dokey="$1"case $key in-e|--extension)EXTENSION="$2"shift # past argumentshift # past value;;-s|--searchpath)SEARCHPATH="$2"shift # past argumentshift # past value;;-l|--lib)LIBPATH="$2"shift # past argumentshift # past value;;--default)DEFAULT=YESshift # past argument;;*)POSITIONAL+=("$1") # save it in an array for latershift # past argument;;esacdoneset -- "${POSITIONAL[@]}" # restore positional parametersecho FILE EXTENSION = "${EXTENSION}"echo SEARCH PATH = "${SEARCHPATH}"echo LIBRARY PATH = "${LIBPATH}"echo DEFAULT = "${DEFAULT}"echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l)if [[ -n $1 ]]; thenecho "Last line of file specified as non-opt/last argument:"tail -1 "$1"fi
2. 使用等号分隔
实际用法
./myscript.sh -e=conf -s=/etc -l=/usr/lib /etc/hosts
实现脚本
#!/bin/bashfor key in "$@"; docase $key in-e=*|--extension=*)EXTENSION="${key#*=}"shift # past argument=value;;-s=*|--searchpath=*)SEARCHPATH="${key#*=}"shift # past argument=value;;-l=*|--lib=*)LIBPATH="${key#*=}"shift # past argument=value;;--default)DEFAULT=YESshift # past argument with no value;;*);;esacdoneecho "FILE EXTENSION = ${EXTENSION}"echo "SEARCH PATH = ${SEARCHPATH}"echo "LIBRARY PATH = ${LIBPATH}"echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l)if [[ -n $1 ]]; thenecho "Last line of file specified as non-opt/last argument:"tail -1 $1fi |
3. 使用 getopts 工具
实际用法
./myscript.sh -h./myscript.sh -v -f
实现脚本
#!/bin/sh# 重置以防止在前面的shell中使用getopts工具(这是一个POSIX变量)OPTIND=1# 初始化变量名称OUTPUT_FILE=""VERSION=0# getopts的缺点就是它只能处理短选项,如-h,而不能是--help格式while getopts "h?vf:" key; docase "$key" inh|\?)show_helpexit 0;;v)VERSION=1;;f)output_file=$OPTARG;;esacdoneshift $((OPTIND-1))[ "${1:-}" = "--" ] && shiftecho "verbose=$VERSION, output_file='$output_file', Leftovers: $@" |
4. 使用 argbash 工具
这个工具主要提供脚本参数的解析功能,而且不再引用任何第三方库的情况下。一般会比普通脚本多30多行而且,但是效果非常好。
详细信息可以通过官方网站地址了解。
https://argbash.io/generate#results
#!/bin/bash# This is a rather minimal example Argbash potential# Example taken from http://argbash.readthedocs.io/en/stable/example.html# [可选参数]# ARG_OPTIONAL_SINGLE([option], [o], [optional argument help msg])# [可选布尔参数]# ARG_OPTIONAL_BOOLEAN([print], , [boolean optional argument help msg])# [固定参数]# ARG_POSITIONAL_SINGLE([positional-arg], [positional argument help msg], )# [帮助信息]# ARG_HELP([The general script's help msg])# ARGBASH_GO# [ <-- needed because of Argbashecho "Value of --option: $_arg_option"echo "print is $_arg_print"echo "Value of positional-arg: $_arg_positional_arg"# ] <-- needed because of Argbash |
