bashshellunix

Get next Sunday after a given date (bash)


Is there any built-in function to get next Sunday (next Monday, Tuesday, etc.) from a given date using bash shell script? For example, what is the first Sunday after 1-Sep-2014? I expect 7-Sep-2014.

I have searched the answer in google, but only found this function :

date "+%Y%m%d" -d Sun

which is to get next Sunday after today.


Solution

  • I fear date can't do it directly. But you can use brace expansion to get the dates for all the following 7 days and select Sunday from them:

    echo '1-Sep-2014\ +'{1..7}'\ days' | LC_ALL=C xargs -n1 date -d | grep Sun
    

    The LC_ALL=C makes the output of date independent on the current locale.