vinz vinz - 1 year ago 74
Linux Question

BASH: Set the date of the last Monday in a variable

today=`date +%a`

if [ "$today" == "Mon" ]
monday=`date -dmonday +%Y%m%d`
monday=`date -dlast-monday +%Y%m%d`

Is it the best way to set the "monday" variable with the date of the last monday?

Answer Source

actually your logic is not always setting "last monday". if today is monday, you would get current date value.

I feel your logic is ok. however one thing you may concern about is, %a give you a localized weekday name. from man page:

 locale’s abbreviated weekday name

there is another format %u, you could use, to make your script more portable.

%u day of week (1..7); 1 is Monday