开发者

bash shell script for yesterdays date (last working day)

I a开发者_如何学Cm writing a bash script that needs to print the date of the last working day. So for example if the script is run on a Monday, it will print the date for last Friday.

I found that this prints yesterdays date:

date -d '1 day ago' +'%Y/%m/%d'

I also know that I can get the day of the week by using this statement

date +%w

I want to combine these two statements in order to have a little helper script that prints the required date. The logic goes something like this (note: its Pseudo code - I've never written a bash script)

DAY_OF_WEEK = `date +%w`
if (%DAY_OF_WEEK == 1)
   LOOK_BACK = 3
elif   
   LOOK_BACK = 1
fi

echo `date -d '%LOOK_BACK day ago' +'%Y/%m/%d'`

Can someone help by correcting the pseudo code above?

(I am running on Ubuntu 10.0.4)


You were so close:

day_or_week=`date +%w`
if [ $day_or_week == 1 ] ; then
  look_back=3
else
  look_back=1
fi

date -d "$look_back day ago" +'%Y/%m/%d'


Sunday also needs to be checked.

DAY_OF_WEEK=`date +%w`
if [ $DAY_OF_WEEK = 0 ] ; then
  LOOK_BACK=2
elif [ $DAY_OF_WEEK = 1 ] ; then
  LOOK_BACK=3
else
  LOOK_BACK=1
fi

date -d "$LOOK_BACK day ago" +'%Y/%m/%d'


I'm using a Mac, so my date command doesn't have the same -d flag yours seems to, but the following should work if it behaves as you've indicated:

if [[ $(date +%w) == 1 ]]
then
    LOOK_BACK=3
else
    LOOK_BACK=1
fi

date -d "${LOOK_BACK} day ago" +%Y/%m/%d


For OSX (tested on 10.9.2 and 10.13.4), so probably any environment where you are using BSD date.

if [ $(date +%w) == 1 ] ; then
    date -v-3d +'%Y/%m/%d'
else
    date -v-1d +'%Y/%m/%d'
fi

You can check to see if you are using BSD date by

$ man date | grep "BSD General"


Putting the other answers together, I came up with this:

last_workday() {
    from_date="${@:-today}"
    day_of_week=$(date +%w --date="${from_date}")

    if [ ${day_of_week} = "0" ] ; then
        look_back=2
    elif [ ${day_of_week} = "1" ] ; then
        look_back=3
    else
        look_back=1
    fi

    date -d "${from_date} - ${look_back} day" +'%Y/%m/%d'
}

next_workday() {
    from_date="${@:-today}"
    day_of_week=$(date +%w --date="${from_date}")
    if [ ${day_of_week} = "5" ] ; then
        look_forward=3
    elif [ ${day_of_week} = "6" ] ; then
        look_forward=2
    else
        look_back=1
    fi

    date -d "${from_date} + ${look_forward} day" +'%Y/%m/%d'
}

for i in $(seq 16); do
    now=$(date +'%Y/%m/%d' --date="today + ${i} day")
    prev=$(last_workday "${now}")
    next=$(next_workday "${now}")
    echo "${now}:  ${prev} ${next}"
done


A more concise form using a bash inline "ternary" expression:

[[ $(date +%w) == 1 ]] && days=3 || days=1
date -d "$days day ago" +"%Y-%m-%d"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜