shell 编写一个带有进度条的程序安装脚本

需求

使用 shell 写一个 软件安装脚本,带有进度条

示例

#!/bin/bash

# 模拟软件安装的步骤列表
steps=("解压文件" "安装依赖" "配置设置" "复制文件" "")

# 计算总步骤数
total_steps=${#steps[@]}

# 安装进度的初始值
progress=0

# 打印安装进度函数
print_progress() {
    local current_step=$1
    local percentage=$2
    local step=$3

    # 清除当前行
    printf "\r\033[K"

    # 构建进度条字符串
    local progress_bar=$(printf "[%-${total_steps}s] %d%%" "$(yes "#" | head -n $current_step | tr -d '\n')" "$percentage")


    # 打印安装进度
    printf "安装进度: %s %s" "$progress_bar" "$step"
}

# 循环执行每个步骤
for ((i=0; i<total_steps; i++)); do
    step=${steps[$i]}

    # 模拟每个步骤的安装操作
    sleep 1

    # 更新进度
    ((progress = (i+1) * 100 / total_steps))

    # 打印安装进度
    print_progress "$((i+1))" "$progress" "$step"
done

# 打印安装完成消息
printf "\n软件安装完成!\n"

在这个示例中,使用 ANSI 转义序列来实现覆盖原来的打印信息,并保持进度条在同一行显示。通过使用 \r 进行回车,然后使用 \033[K 清除当前行的内容,可以实现覆盖效果。

在 print_progress 函数中,首先清除当前行的内容,然后构建进度条字符串,并使用 \r 实现回车到行首的效果。进度条字符串包含了当前步骤的填充部分和进度百分比。

最后,通过调用 print_progress 函数来打印安装进度,并在安装完成后打印安装完成消息。

效果

shell 编写一个带有进度条的程序安装脚本_第1张图片

你可能感兴趣的:(Linux,shell,进度条)