# 模拟后台任务:将进度写入临时文件 worker_task() { localid=$1 local steps=$2 local tmp_file="progress_${id}.tmp" for ((i=0; i<=steps; i++)); do echo"$i" > "$tmp_file" sleep 0.1 # 模拟网络延迟或处理耗时 done }
# 函数:并行任务进度条 # 参数:$1 = 任务总数, $2 = 每个任务的步数 parallel_progress_bar() { local total_tasks=$1 local steps_per_task=$2 local bar_width=20
# 1. 清理旧的临时文件 rm -f progress_*.tmp
# 2. 启动后台任务,并记录PID local pids=() for ((t=1; t<=total_tasks; t++)); do worker_task $t$steps_per_task & pids+=($!) done
# 3. 隐藏光标 tput civis 2>/dev/null
# 预先打印空行占位,方便后续光标上移覆盖 for ((i=0; i<=total_tasks; i++)); doecho""; done
# 4. 主循环:轮询临时文件并刷新UI whiletrue; do local all_done=true local total_current=0 local total_all=$((total_tasks * steps_per_task)) local ui_output=""
# 收集各个子任务的进度 for ((t=1; t<=total_tasks; t++)); do local tmp_file="progress_${t}.tmp" local current=0 if [ -f "$tmp_file" ]; then current=$(cat"$tmp_file") fi total_current=$((total_current + current))
# 构建单任务进度条UI local filled=$((current * bar_width / steps_per_task)) local bar=$(printf"%${filled}s" | tr' ''#') local space=$(printf"%$((bar_width - filled))s") ui_output+="Task ${t}: [${bar}${space}] ${current}/${steps_per_task}\n"
if [ "$current" -lt "$steps_per_task" ]; then all_done=false fi done
# 构建总进度条UI local total_percent=$((total_current * 100 / total_all)) local total_filled=$((total_current * (bar_width + 10) / total_all)) # 稍微宽一点 local total_bar=$(printf"%${total_filled}s" | tr' ''=') local total_space=$(printf"%$((bar_width + 10 - total_filled))s")