Shell脚本中忽略大小写检查文件是否存在的方法
忽略大小写检查文件是否存在的Shell实现方法
下面提供几种实用的Shell脚本实现方式,解决传递文件名参数时忽略大小写检查文件存在性的问题:
方法1:使用find命令(跨Shell兼容)
find的-iname参数支持忽略大小写匹配文件名,适合大多数Shell环境:
# 从传入参数中提取目标文件名 target_file=$(echo "$1" | sed 's/--fileName=//') # 指定要检查的目标目录(这里以当前目录为例,可替换为实际路径) target_dir="./" # 查找目标目录下是否存在匹配的文件(不递归子目录) if find "$target_dir" -maxdepth 1 -type f -iname "$target_file" | grep -q .; then echo "文件存在" else echo "文件不存在" fi
-maxdepth 1限制仅查找当前目录,避免递归子目录;-type f确保只匹配普通文件(排除目录);grep -q .用于静默检查find是否有输出,无输出则表示无匹配文件。
方法2:使用Bash扩展nocaseglob
如果脚本基于Bash运行,可以开启nocaseglob选项让文件名匹配忽略大小写:
# 开启忽略大小写的文件名匹配 shopt -s nocaseglob target_file=$(echo "$1" | sed 's/--fileName=//') target_dir="./" # 直接用文件存在性检查语法 if [ -e "$target_dir/$target_file" ]; then echo "文件存在" else echo "文件不存在" fi # 关闭nocaseglob,避免影响后续脚本逻辑 shopt -u nocaseglob
方法3:遍历目录+大小写转换对比
这种方法不依赖任何扩展特性,兼容性最好:
# 提取目标文件名并转换为小写 target_file=$(echo "$1" | sed 's/--fileName=//' | tr '[:upper:]' '[:lower:]') target_dir="./" file_exists=0 # 遍历目标目录下的所有条目 for item in "$target_dir"/*; do # 跳过不存在的条目(比如目录为空时) [ -e "$item" ] || continue # 获取条目名称并转换为小写 item_name=$(basename "$item" | tr '[:upper:]' '[:lower:]') if [ "$item_name" = "$target_file" ]; then file_exists=1 break fi done if [ $file_exists -eq 1 ]; then echo "文件存在" else echo "文件不存在" fi
内容的提问来源于stack exchange,提问作者Mayank Upadhyay
相关产品推荐
相关产品推荐

