Quantcast
Channel: Bashタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 2914

シェルスクリプトで土日判定を行う方法

$
0
0
業務で、yyyymmdd形式で渡された日付データの土日祝日判定を、 シェルスクリプトで行いたいという経緯があり、作成しました。 今回はその中の土日判定のみについて紹介します。 完成品 # # description # # 土日であるか調べる # # Args: # # $1 - 判定する日時(yyyymmdd形式) # # return: # 土日の場合 0 # 平日の場合 1 # isWeekend () { local saturday=6 local sunday=7 local _date="$1" if [ $saturday -eq `date -d $_date '+%u'` -o $sunday -eq `date -d $_date '+%u'` ]; then return 0 else return 1 fi } current_date=`date '+%Y%m%d'` if `isWeekend "$current_date"` ; then echo "the weekend" else echo "not the weekend" fi 現在の日付が土曜日or日曜日なら the weekend が出力され、そうでない場合 not the weekend が出力される。 実装について dateコマンドを下記のようなオプションで実行した際に、曜日に対応する数値が得られる。 # -dで指定した日付に対して、%u(曜日[1-7])を出力している # 20220122は土曜日なので、6が出力される date -d 20220122 '+%u' 6 %uの対応表 月 火 水 木 金 土 日 1 2 3 4 5 6 7 実際のコードでは下記にて、土日変数にそれぞれ6と7を割り当てている。 isWeekend () { local saturday=6 local sunday=7 # 現在の日付が入ってくる(yyyymmdd形式) local _date="$1" # 現在の日付を数値にしたものが 6 or 7の場合 で判定している if [ $saturday -eq `date -d $_date '+%u'` -o $sunday -eq `date -d $_date '+%u'` ]; then return 0 else return 1 fi 下記のように最初から曜日の数値を格納してやれば、ワンライナーでも判定できると思われたかもしれないが、 今回業務で行いたかった内容としては、yyyymmdd形式で渡される前提だったため、下記のようにしなかった。 current_date=date '+%u' 曜日判定を1行で完結させる場合はこんな感じ。 if [ 6 -eq `date '+%u'` -o 7 -eq `date '+%u'` ]; then echo "the weekend" fi おまけ このシェルスクリプトは、現在の曜日を固定で判定しているため、 日付が変わらない限り常に "the weekend" or "not the weekend"が出力される。 どちらの出力も確認したいという場合は、下記のように書き換えれば2日後で判定することができる。 # current_date=`date '+%Y%m%d'` current_date=`date '+%Y%m%d' --date "2 day"` もちろん下記のようにベタ書きしてしまってもよい。 current_date="20220124"

Viewing all articles
Browse latest Browse all 2914

Trending Articles