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

Bash で日付を 1 日ずつ進めながら処理を実行する方法

Last updated at Posted at 2025-08-29

はじめに

シェルスクリプトで「指定した日付の範囲を 1 日ずつ進めて処理をしたい」ことはよくあります。今回は Bash + date コマンドを使って、日付をループさせるシンプルな方法を紹介します。

サンプルコード

#!/bin/bash

start="20250101"
end="20250105"

while [ "$start" -le "$end" ]; do
  echo "$start"
  start=$(date -d "$start + 1day" +%Y%m%d)
  sleep 1
done

実行結果

20250101
20250102
20250103
20250104
20250105

1 秒ごとに日付が 1 日ずつ進んで出力されることが確認できます。

解説

1. date -d

このコマンドで、20250101 の翌日を YYYYMMDD 形式で取得できます。
つまり、+ 1day を繰り返すことで簡単に日付をインクリメントできます。

date -d "20250101 + 1day" +%Y%m%d

2. while ループ

開始日 (start) が終了日 (end) を超えるまでループを続けます。
この比較は文字列ではなく「数値比較」として働きます。20250101 形式であれば -le でそのまま判定できます。

start="20250101"
end="20250105"

while [ "$start" -le "$end" ]; do
    ~
done

3. sleep 1

処理の間に 1 秒の待機を入れています。不要なら削除して OK です。

sleep 1

応用例

日付ごとにログファイルを処理する

while [ "$start" -le "$end" ]; do
  cat "/var/log/app/${start}.log"
  start=$(date -d "$start + 1day" +%Y%m%d)
done

週単位・月単位に増やす

date -d "$start + 1week" +%Y%m%d
date -d "$start + 1month" +%Y%m%d

数字単位で増やす

#!/bin/bash

start=1
end=5

while [ "$start" -le "$end" ]; do
  echo "$start"
  start=$((start + 1))
  sleep 1
done

まとめ

こちらはあくまでもループの外枠の仕組みとなります。
ループの中でどう使うか次第でいろいろと応用できると思いますので
ぜひいろんなことに活用してみてください。

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