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 函数来打印安装进度,并在安装完成后打印安装完成消息。

细节

local progress_bar=$(printf "[%-${total_steps}s] %d%%" "$(yes "#" | head -n $current_step | tr -d '\n')" "$percentage")
这行如何理解 ?

这行代码是用来构建进度条字符串 progress_bar 的。

逐步解释这行代码的含义:

  1. yes "#" | head -n $current_step:这部分代码使用 yes 命令生成一个无限重复的 # 字符串,并使用 head -n $current_step 命令截取前 $current_step 行。这样就生成了一个由 # 字符构成的字符串,长度为 $current_step

  2. tr -d '\n':这部分代码使用 tr 命令删除字符串中的换行符 \n,即将多行字符串合并为单行。

  3. $percentage:这部分代码是进度百分比的数值。

  4. $(printf "[%-${total_steps}s] %d%%" ...):这部分代码使用 printf 格式化字符串的功能,将 $current_step 行的 # 字符串和进度百分比插入到格式化的字符串中。

具体解释如下:

  • [%-${total_steps}s]:这是一个格式化字符串,表示一个固定长度为 $total_steps 的方括号字符串,其中 -% 表示左对齐,${total_steps}s 表示字符串占位符,用来填充 # 字符。

  • %d%%:这是一个格式化字符串,表示一个整数占位符,用来填充进度百分比的数值,同时后面的 %% 表示打印一个百分号字符 %

最终,progress_bar 字符串的内容类似于 [##### ] 50%,其中 # 的数量和进度百分比随着安装进度的增加而变化。

效果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_47406832/article/details/132482385
今日推荐