Mykhaylo Adamovych
Mykhaylo Adamovych

Reputation: 20966

Set next/previous weekday

With following code I can roll day in Linux back and forth.

date -s 'tomorrow'
date -s 'yesterday'

I would like to do the same but skip weekends.

Upvotes: 3

Views: 1171

Answers (3)

Mykhaylo Adamovych
Mykhaylo Adamovych

Reputation: 20966

if [[ $( date +%u ) = 5 ]] ; then date --set="+3 days" ; else date --set="+1 days" ; fi
if [[ $( date +%u ) = 1 ]] ; then date --set="-3 days" ; else date --set="-1 days" ; fi

Upvotes: 0

Algorithmic Canary
Algorithmic Canary

Reputation: 742

This script sets the day to the next weekday. Before forewarned that these scripts strip out the time of day when jumping over the weekend. Also, they are not portable to limited shells like busybox.

week_day=$(date +%w) #get the week day as a number from 0
if [[ $week_day == 5 || $week_day == 6 ]] #check to see if it is Fri or Sat
then date -s 'next monday' #if it is Fri or Sat, the set day to next monday
else date -s tomorrow #it is a different day of the week, go to the next day
fi

The last week day

week_day=$(date +%w) #get the week day as a number from 0 to 6 starting with 0 as Sunday
if [[ $week_day == 0 || $week_day == 1 ]] #check to see if it is Sun or Mon 
then date -s 'last friday' #if it is Sun or Mon, the set day to last friday
else date -s yesterday #it is a different day of the week, go to yesterday
fi

Upvotes: 2

GMichael
GMichael

Reputation: 2776

The following gives you next working day (for bash):

if [[ $( date +%u ) -eq 5 ]] ; then date --date="next Monday" ; else date --date="next day" ; fi

Upvotes: 3

Related Questions