0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CLIアプリで行内で進捗を表示する方法

0
Last updated at Posted at 2026-02-11

CLIアプリで時間のかかる処理を行うとき、進捗状況のパーセンテージを改行を挟まずに同じ行内で表示したい場合のやり方です。
復帰文字(\r)を使ってカーソル位置を行頭に戻し、進捗状況を繰り返し出力することで実現できます。

サンプル(Java)
int max=100000 // 繰り返しの最大数。ここでは100000回
for (int i=0; i<max; i++) {
  // "message i/max (prog%)"を表示し、末尾の復帰(\r)でカーソル位置を行頭に戻す
  if ((i % 1000) == 0) { // 進捗を毎回出力すると遅くなるので間引く
    System.out.print(String.format("message %d/%d (%.1f%%)\r", i, max, (i*100F/max));
  }
  
  // 繰り返し処理
}
// 最後に"message max/max (100.0%)"の表示をして、改行(\n)で次の行へ
System.out.print(String.format("message %d/%d (%.1f%%)\n", max, max, (max*100F/max));

シェルスクリプトでも echo -en "\r" を使って同じことができます。
Pythonなど他の処理系でも同じやり方で書けます。

サンプル(bash)
#!/bin/bash

max=100000
for i in `seq 0 $max`; do
  # 進捗表示
  if [ $(( $i % 100 )) -eq 0 ]; then
    echo -ne "message ${i}/${max} ($(( $i * 100 / $max ))%)\r"
  fi

  # 繰り返し処理
done

echo "message $max/$max (100%)"

メッセージの部分も書き換えられますが、出力する文字数が前より短いと前の出力の末尾がCLI上に残ります。空白で埋めるなどの工夫が必要です。
また画面表示は意外と時間がかかるため、繰り返し数が多い場合にサンプルにあるような間引き処理をしないと速度が目に見えて下がります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?