Bash脚本getopts函数无法识别-h帮助选项的问题及修复方案
Bash脚本getopts无法识别-h参数的修复方案
问题根因
getopts解析命令行选项时仅会更新内置变量OPTIND记录下一个待处理参数的索引,不会自动删除已经解析完成的选项参数。原脚本未在getopts解析完成后执行偏移操作,导致后续遍历参数的循环会将-h识别为普通文件路径照常处理。- 原代码无效选项分支存在语法错误:
echo: "Invalid option"多写了冒号,执行时会抛出command not found错误。
修复后完整代码
#!/bin/bash trash=~/TRASH if [ ! -e "$trash" ]; then mkdir "$trash" elif [ ! -d "$trash" ]; then echo "$0: error: $trash is not a directory"; exit 1 fi while getopts "h" options; do case $options in h) echo "This is the help option." exit;; \?) echo "Invalid option" exit;; esac done # 移除已解析的选项参数 shift $((OPTIND - 1)) while [ $# -gt 0 ]; do if [ ! -e "$1" ]; then echo "$0: error: tried to delete file that does not exist: $1" shift continue fi tarname="$1.tar" tar -cf "$tarname" "$1" mv "$tarname" "$trash" rm -rf "$1" shift done echo "Cleaning $trash directory" now=`date +%s` cd "$trash" for f in *; do if [ -f "$f" ] || [ -d "$f" ]; then fileage=$(stat -c '%Y' "$f") if [ $((now-fileage)) -gt $((60*60*24*2)) ]; then rm -rf "$f" fi fi done
核心修改点说明
- 在
getopts循环结束后新增shift $((OPTIND - 1)),将参数指针偏移到第一个非选项参数位置,清除所有已解析的选项参数,避免后续逻辑将选项识别为文件 - 修复
echo: "Invalid option"的语法错误,删除echo后的多余冒号 - 所有变量使用双引号包裹,避免路径含空格时执行异常
- 将遍历回收站文件的
for f in \ls`改为for f in *`,新增文件存在性判断,避免空目录或者特殊文件名导致的执行错误
内容的提问来源于stack exchange,提问作者Nuno
相关产品推荐
相关产品推荐

