はじめに
シェルスクリプトで一連の処理を書く際に、プログレスバーを利用すると進捗がわかりやすくなります。
スクリプト
progress.sh
#!/bin/sh
# 最大値の設定
max=100
# プログレスバーを描画する関数
progress_bar() {
local progress=$1
local width=50 # プログレスバーの幅
local completed=$((progress * width / max))
printf "["
if [ $progress -lt $max ]; then
# 100%未満の場合
if [ $completed -eq $((width - 1)) ]; then
# 99%の場合、最後の2文字を "=="にする
printf "%0.s=" $(seq 1 $((completed + 1)))
else
printf "%0.s=" $(seq 1 $completed)
printf ">" # 右矢印
local remaining=$((width - completed - 1))
printf "%0.s-" $(seq 1 $remaining)
fi
else
# 100%の場合
printf "%0.s=" $(seq 1 $width)
fi
printf "] %d%%" "$progress"
tput el # 行末までを消去
}
# 進捗バーを100%まで表示
for i in $(seq 0 $max); do
tput civis # カーソルを非表示にする
progress_bar "$i"
sleep 0.05 # プログレスバーの更新速度を調整
if [ $i -lt $max ]; then
tput cr # 100%未満の場合、行の先頭にカーソルを戻す
fi
done
tput cnorm # カーソルを再表示
echo -e "\e[32m\n完了しました!\e[0m"
exit 0