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

如何将Bash进度条的多分支if结构替换为for循环优化代码

Bash进度条代码优化方案

你当前的多分支if实现虽然能正常运行,但确实可以通过动态计算的方式大幅简化代码,让结构更简洁易维护。以下是几种优化思路和实现:

原代码回顾

progress_bar () {
PROGRESS=`expr $( cat $CONTROL_FILE ) - 100 | tr "-" "\r"`
clear
    if [ "$PROGRESS" -eq 10 ]
    then
    echo -n "$PROGRESS % [#         ] "
    fi
    if [ $PROGRESS -eq 20 ]
    then
    echo -n "$PROGRESS % [##        ] "
    fi
    if [ $PROGRESS -eq 30 ]
    then
    echo -n "$PROGRESS % [###       ] "
    fi
    if [ $PROGRESS -eq 40 ]
    then
            echo -n "$PROGRESS % [####      ] "
    fi
    if [ $PROGRESS -eq 50 ]
    then
            echo -n "$PROGRESS % [#####     ] "
    fi
    if [ $PROGRESS -eq 60 ]
    then
            echo -n "$PROGRESS % [######    ] "
    fi
    if [ $PROGRESS -eq 70 ]
    then
            echo -n "$PROGRESS % [#######   ] "
    fi
    if [ $PROGRESS -eq 80 ]
    then
            echo -n "$PROGRESS % [########  ] "
    fi
    if [ $PROGRESS -eq 90 ]
    then
            echo -n "$PROGRESS % [######### ] "
    fi
    if [ $PROGRESS -eq 100 ]
    then
            echo "$PROGRESS % [##########]"
    fi}

优化方案1:动态生成进度条(推荐)

通过计算进度值对应的#数量和空格数量,直接生成进度条内容,彻底去掉所有冗余的if判断:

progress_bar () {
    # 优化命令替换写法,用$()替代反引号,可读性更强
    PROGRESS=$(expr $(cat "$CONTROL_FILE") - 100 | tr "-" "\r")
    # 计算进度条中#的数量(进度为10的倍数,直接除以10)
    hash_count=$((PROGRESS / 10))
    # 计算剩余空格数量(总长度固定为10个字符)
    space_count=$((10 - hash_count))
    
    # 生成#字符串:重复hash_count次#
    hashes=$(printf "%${hash_count}s" "" | tr ' ' '#')
    # 生成空格字符串:重复space_count次空格
    spaces=$(printf "%${space_count}s" "")
    
    # 输出进度条:100%时换行,其他情况保持在同一行更新
    if [ "$PROGRESS" -eq 100 ]; then
        echo "$PROGRESS % [$hashes$spaces]"
    else
        # 用\r回到行首,避免每次清屏,体验更流畅
        echo -ne "\r$PROGRESS % [$hashes$spaces] "
    fi
}

优化方案2:用循环生成字符(兼容旧版Bash)

如果你的Bash版本较低(低于4.x),可以用for循环来生成对应的#和空格:

progress_bar () {
    PROGRESS=$(expr $(cat "$CONTROL_FILE") - 100 | tr "-" "\r")
    hash_count=$((PROGRESS / 10))
    space_count=$((10 - hash_count))
    
    hashes=""
    for ((i=0; i<hash_count; i++)); do
        hashes+="#"
    done
    
    spaces=""
    for ((i=0; i<space_count; i++)); do
        spaces+=" "
    done
    
    if [ "$PROGRESS" -eq 100 ]; then
        echo "$PROGRESS % [$hashes$spaces]"
    else
        echo -ne "\r$PROGRESS % [$hashes$spaces] "
    fi
}

优化亮点

  • 彻底移除了10个重复的if分支,代码行数大幅减少,维护成本降低
  • 动态计算字符数量,后续要调整进度条长度(比如改成20个字符),只需修改10这个数字即可
  • 替换了老旧的反引号写法,使用更现代的$()进行命令替换
  • 优化了输出方式,用\r替代clear,避免频繁清屏,进度条在同一行更新,视觉体验更流畅

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:10:40