You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

检测目录名首尾空格的Shell脚本出现语法错误,寻求解决方法

修复检测目录名首尾空格的Shell脚本错误

以下是你提供的原Shell脚本及报错信息:

原脚本

check_directory_names() {
    local invalid_dirs=()
    while IFS=read -r -d '' dir; do
        if [[ "$dir" =~ \ ]]; then
            invalid_dirs+("$dir")
        fi
    done < <(find . -type d -print0)
    
    if [ ${#invalid_dirs[@]} - ne 0 ]; then
    echo "Directories with spaces detected:"
    printf '%s\n' "${invalid_dirs[@]}"
    return 1
    fi
}

报错信息

line 7: syntax error in conditional expression: unexpected token `;'
line 7: syntax error near `;'
line 7: `        if [[ "$dir" =~ \ ]]; then'

错误分析及修复

1. 正则表达式语法错误

原脚本里的[[ "$dir" =~ \ ]]写法存在两个问题:

  • bash的=~操作符后接正则时,空格不需要转义,单独的\ 属于语法错误;
  • 原正则逻辑是匹配任意位置的空格,和你要检测目录名开头或结尾空格的需求不符。

正确的正则应匹配开头空白字符(^[[:space:]])或结尾空白字符([[:space:]]$),写成[[ "$dir" =~ ^[[:space:]]|[[:space:]]$ ]]能兼容空格、制表符等所有空白字符,若只想检测空格,可简化为[[ "$dir" =~ ^ | $ ]]。

2. 条件运算符格式错误

第二个if判断里的- ne中间多了空格,bash的数值比较运算符-ne(不等于)是连写的,不能拆分。

修复后的完整脚本

check_directory_names() {
    local invalid_dirs=()
    while IFS=read -r -d '' dir; do
        # 检测目录名开头或结尾是否包含空白字符
        if [[ "$dir" =~ ^[[:space:]]|[[:space:]]$ ]]; then
            invalid_dirs+=("$dir")
        fi
    done < <(find . -type d -print0)
    
    if [ ${#invalid_dirs[@]} -ne 0 ]; then
        echo "检测到首尾含空白字符的目录:"
        printf '%s\n' "${invalid_dirs[@]}"
        return 1
    fi
}

额外说明

  • find ... -print0配合read -d ''的写法是正确的,能稳定处理包含特殊字符的目录名;
  • 若仅需检测空格而非所有空白字符,将正则替换为^ | $即可。

内容的提问来源于stack exchange,提问作者ArunK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 21:46:18