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

Bash脚本:检查文件空白内容及修复失效函数求助

修复处理含空白字符文件的Bash函数

原函数的问题集中在这几个点:

  • 判断文件存在时,[ -f $file ]里的$file未加双引号,一旦文件名带空格或制表符,会被Shell拆成多个参数,导致判断逻辑出错
  • 用variable=echo $value``赋值时,echo $value会自动把连续空白(空格、制表符)压缩成单个,还会解析通配符,直接丢失了原始的空白格式
  • 循环内每次覆盖variable,最终只保留文件最后一行的值(这个是原逻辑,若需收集所有行可后续调整)

修复后的函数代码:

get_value()
{
    file="/u01/app/file.lst"
    # 变量加双引号,避免空白字符被错误解析
    if [ -f "$file" ]; then
        echo "file.lst file exists, Checking values"
        # 同样给变量加双引号
        if [ -s "$file" ]; then
            # IFS= read -r 已能保留行内空白,直接赋值即可
            while IFS= read -r value
            do
                variable="$value"
            done < "$file"
            echo "Variable values is : $variable"
        else
            echo "file.lst file is empty,Default value for variable is 10"
            variable=10
            echo "$variable"
        fi
    else
        echo "file.lst file does not exists, Default value for variable is 10"
        variable=10
        echo "$variable"
    fi
}

关键修改细节:

  • 所有变量引用(如$file、$variable)都加上双引号,防止Shell对空白字符进行拆分和解析
  • 去掉多余的echo赋值步骤,直接用variable="$value"保留行内的所有空白字符(包括空格、制表符)
  • 修正了原函数里的语法错误(doesnot改为does not,移除多余逗号)

如果需要收集文件中所有行的内容(而非仅保留最后一行),可以改用数组存储:

get_value()
{
    file="/u01/app/file.lst"
    if [ -f "$file" ]; then
        echo "file.lst file exists, Checking values"
        if [ -s "$file" ]; then
            # 初始化数组
            variables=()
            while IFS= read -r value
            do
                variables+=("$value")
            done < "$file"
            echo "All variable values:"
            # 遍历数组输出所有行
            for val in "${variables[@]}"
            do
                echo "$val"
            done
        else
            echo "file.lst file is empty,Default value for variable is 10"
            variable=10
            echo "$variable"
        fi
    else
        echo "file.lst file does not exists, Default value for variable is 10"
        variable=10
        echo "$variable"
    fi
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:55:49