はじめに
バッジ処理などを実行する際に、一ヶ月分の日付のデータに対してスクリプトを実行することがよくあります。
例えば、2021年6月分のデータを実行する際に
python hoge.py 2021 6 1
python hoge.py 2021 6 2
python hoge.py 2021 6 3
python hoge.py 2021 6 4
...
python hoge.py 2021 6 30
と実行するのは骨が折れます。
そこで本記事では、そのような状況で私がよく使用するシェルスクリプトを雛形を紹介させていただきます。
dateコマンドのオプションの違いがあるため、2パターン紹介します。
echoの部分を改造して使用していただけると幸いです。
Linuxの場合
シェルスクリプト本文
#!/bin/sh
# 途中で処理が失敗したらそこで処理を打ち止めにする設定
set -eu
# 引数
# $1 対象の年 ex) 2021
# $2 対象の月[0埋めなし] ex) 6
year=$1
month=$2
# 月の情報を2桁かつ0埋めの状態にする
tmp_month=0${month}
month_with_zero_pad=${tmp_month: -2}
# 処理の開始の日付と終了の日付(1ヶ月後の日付)を定義する
start_date=${year}${month_with_zero_pad}01
end_date=`date -d "$start_date 1month" "+%Y%m%d"`
# 繰り返し文の中で処理の対象となる日付
target_date=${start_date}
# 1日分ずつ処理する繰り返し文
while [ 1 ] ; do
# 対象の日付がend_dateに達したら繰り返し文を抜ける
if [ $target_date = $end_date ] ; then
break
fi
echo target:${target_date}
# 日付部分を抜き出す
day=${target_date:6:2}
# dayのゼロ埋めをなくしたい
if [ ${day:0:1} = 0 ] ; then
day=${target_date:7:1}
fi
# 処理を実行する
echo year:${year}, month:${month}, day:${day}
# 日付をインクリメントする
target_date=`date -d "$target_date 1day" "+%Y%m%d"`
done
echo ${year}/${month} complete!
実行
$ sh linux_1month.sh 2021 6
target:20210601
year:2021, month:6, day:1
target:20210602
year:2021, month:6, day:2
target:20210603
year:2021, month:6, day:3
target:20210604
year:2021, month:6, day:4
...
target:20210629
year:2021, month:6, day:29
target:20210630
year:2021, month:6, day:30
2021/6 complete!
MacOSの場合(BSD Unixベース)
シェルスクリプト本文
#!/bin/sh
# 途中で処理が失敗したらそこで処理を打ち止めにする設定
set -eu
# 引数
# $1 対象の年 ex) 2021
# $2 対象の月[0埋めなし] ex) 6
year=$1
month=$2
# 月の情報を2桁かつ0埋めの状態にする
tmp_month=0${month}
month_with_zero_pad=${tmp_month: -2}
# 処理の開始の日付と終了の日付(1ヶ月後の日付)を定義する
start_date=${year}${month_with_zero_pad}01
end_date=`date -v+1m -j -f "%Y%m%d" $start_date "+%Y%m%d"`
# 繰り返し文の中で処理の対象となる日付
target_date=${start_date}
# 1日分ずつ処理する繰り返し文
while [ 1 ] ; do
# 対象の日付がend_dateに達したら繰り返し文を抜ける
if [ $target_date = $end_date ] ; then
break
fi
echo target:${target_date}
# 日付部分を抜き出す
day=${target_date:6:2}
# dayのゼロ埋めをなくしたい
if [ ${day:0:1} = 0 ] ; then
day=${target_date:7:1}
fi
# 処理を実行する
echo year:${year}, month:${month}, day:${day}
# 日付をインクリメントする
target_date=`date -v+1d -j -f "%Y%m%d" $target_date "+%Y%m%d"`
done
echo ${year}/${month} complete!
実行
$ sh macos_1month.sh 2021 6
target:20210601
year:2021, month:6, day:1
target:20210602
year:2021, month:6, day:2
target:20210603
year:2021, month:6, day:3
target:20210604
year:2021, month:6, day:4
...
target:20210629
year:2021, month:6, day:29
target:20210630
year:2021, month:6, day:30
2021/6 complete!
最後に
今回はよく使うバッジスクリプトについて紹介させていただきました。
結局、日付処理→文字列処理となってしまうあたりがあまりスマートではないなと個人的に感じております。
これが開発などの参考となれば幸いです。