Bash脚本如何统计排除选项后的有效输入参数数量
实现方案
核心逻辑是利用getopts配套的内置变量OPTIND:它会自动记录getopts下一个要处理的参数下标,处理完所有选项后用shift移除已经处理过的选项类参数,剩下的就是你需要的路径参数,直接校验剩余参数数量即可。
注意:如果你示例中的-e选项需要接收参数(比如示例里的someparameter),需要把getopts的选项字符串从:he改成:he:,给e后面加冒号表示该选项需要带参数。
修改后的完整脚本
#!/bin/bash set -e Help() { # Display Help echo -e "I am the help menu" echo -e "Usage: $0 [OPTIONS] <file1> <file2>" echo -e "Options:" echo -e " -h Show help message" echo -e " -e <param> Exclude files with specified parameter" } ############################################################ # Main program # Process the input options. e后面加冒号表示该选项需要带参数 while getopts ":he:" option; do case $option in h) # display Help Help exit 0;; e) # Exclude Files EXCLUDE_PARAM="$OPTARG" echo -e "e option was selected, exclude param: $EXCLUDE_PARAM";; :) # 缺少选项参数的异常处理 echo "Error: Option -$OPTARG requires an argument." >&2 exit 1;; \?) # Invalid option echo -e "Error: Invalid option -$OPTARG" >&2 exit 1;; esac done # 移除所有已经处理过的选项和选项参数 shift $((OPTIND - 1)) # 校验剩余有效参数数量必须为2 if [ $# -ne 2 ]; then echo "Error: You must provide exactly 2 file/directory paths." >&2 Help >&2 exit 1 fi # 现在剩余的$1 $2就是两个路径参数 file1="$1" file2="$2" echo "file1: $file1" echo "file2: $file2"
功能验证
完全符合你要求的运行逻辑:
- 执行
./foo -e "someparameter" file1 file2:程序正常运行,正确识别-e的参数和两个路径 - 执行
./foo file1:剩余参数只有1个,触发错误提示并退出 - 执行
./foo file1 file2 file3:剩余参数有3个,触发错误提示并退出
内容的提问来源于stack exchange,提问作者user8458838
相关产品推荐
相关产品推荐

