1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

シェルスクリプトでプログレスバーをつくろう

Last updated at Posted at 2024-10-17

はじめに

シェルスクリプトで一連の処理を書く際に、プログレスバーを利用すると進捗がわかりやすくなります。

例:
スクリーンショット 2024-10-17 23.24.28.png

スクリプト

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
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?