Bash脚本getopts参数异常、清理功能报错、最大文件查询问题求助
Bash脚本参数异常修复方案
1. -r参数报错修复
问题原因
- case兜底分支(
*))存在“无效参数”输出逻辑,处理完-r选项后循环未正确终止,会触发兜底分支输出错误 - 目录不存在时执行的
continue会让循环继续执行,重复触发兜底错误
修复后代码
while getopts "hr:t:s:u:" options; do case $options in h) # 此处补充你的帮助信息逻辑 exit 0 ;; r) tgtdir="${OPTARG}" if [ ! -d "${tgtdir}" ]; then echo "$0: error: tried to delete directory that does not exist: ${tgtdir}" exit 1 # 出错直接退出,避免走后续循环逻辑 fi tarname="${tgtdir}.tar" tar -cf "$tarname" "${tgtdir}" mv "$tarname" "${trash}" # 变量加引号避免路径带空格出错 rm -r "${tgtdir}" exit 0 # 执行完成直接退出,避免触发兜底分支 ;; # 其他参数逻辑 *) echo "$0: error: invalid option -${OPTARG}" exit 1 ;; esac done
2. -t参数逻辑异常修复
问题原因
- 变量赋值语法错误:
now =date +%s``中=两侧不能有空格,导致now变量为空,时间计算逻辑完全失效 for f in \ls``写法不兼容带空格/特殊字符的文件名,会出现遍历错误- 每遍历一个文件就输出一次结果,逻辑不合理
- 未判断
cd $trash是否执行成功,可能误删其他目录的文件
修复后代码
t) tgthour="${OPTARG}" # 校验输入是否为正整数 if ! [[ "${tgthour}" =~ ^[0-9]+$ ]]; then echo "$0: error: -t parameter must be a positive integer" exit 1 fi now=$(date +%s) # 校验回收站路径是否存在 if [ ! -d "${trash}" ]; then echo "$0: error: trash directory ${trash} does not exist" exit 1 fi cd "${trash}" || exit 1 has_cleaned=0 # 用glob遍历避免特殊字符文件名问题 for f in *; do # 跳过不存在的占位符(避免空目录遍历到*本身) [ -e "$f" ] || continue fileage=$(stat -c '%Y' "$f") if [ $((now - fileage)) -gt $((3600 * tgthour)) ]; then rm -rf "$f" has_cleaned=1 fi done if [ "${has_cleaned}" -eq 1 ]; then echo "Cleaned files older than ${tgthour} hours in directory ${trash}" else echo "Nothing to clean in directory ${trash}" fi exit 0 ;;
3. -s参数报错修复
问题原因
- 未校验输入参数是否为正整数,传入非数字值会导致find命令抛出参数无效错误
- 未判断
cd $trash是否执行成功,可能误删其他目录的文件
修复后代码
s) tgtsize="${OPTARG}" # 校验输入是否为正整数 if ! [[ "${tgtsize}" =~ ^[0-9]+$ ]]; then echo "$0: error: -s parameter must be a positive integer (unit: KB)" exit 1 fi if [ ! -d "${trash}" ]; then echo "$0: error: trash directory ${trash} does not exist" exit 1 fi find "${trash}" -type f -size +"${tgtsize}"k -delete echo "Deleted all files larger than ${tgtsize}KB in ${trash}" exit 0 ;;
4. -u参数返回结果异常修复
问题原因
- 代码中
head-1缺少空格,属于命令拼写错误,会导致执行失败 - 未给
$trash加引号,路径带空格时会执行失败
修复后代码
u) if [ ! -d "${trash}" ]; then echo "$0: error: trash directory ${trash} does not exist" exit 1 fi # 加引号避免路径空格问题,修正head命令拼写 find "${trash}" -type f -printf '%s %p\n' | sort -nr | head -1 exit 0 ;;
内容的提问来源于stack exchange,提问作者Nuno
相关产品推荐
相关产品推荐

