Shibu
Shibu

Reputation: 1542

Get first date of current month in MacOS terminal

uisng the command echo $(date "+%F" -d "$(date +'%Y-%m-01') 0 month") i can get the first date of that month. but the same is not working on mac terminal. What needs to be changed?

echo $(date "+%F" -d "$(date +'%Y-%m-01') 0 month")
date: illegal time format
usage: date [-jnRu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ...
            [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]

Upvotes: 2

Views: 1418

Answers (1)

Inian
Inian

Reputation: 85663

The date libraries in *BSD and GNU systems are different and the options supported vary between them. The -d flag which supports a myriad of functions in GNU date is replaced by the -f option in BSD (See FreeBSD Manual Page for date)

For your requirement though, you need the time adjust flag using the -v flag. So the first day of the current month should be

date -v1d -v"$(date '+%m')"m '+%F'
  • The -v1d is a time adjust flag to move to the first day of the month
  • In -v"$(date '+%m')"m, we get the current month number using date '+%m' and use it to populate the month adjust field. So e.g. for Aug 2020, its set to -v8m
  • The '+%F' is to print the date in YYYY-MM-DD format. If its not supported in your date version, use +%Y-%m-%d explicitly.

Or if your requirement is to print the date for all the months

for mon in {1..12}; do
    date -v1d -v"$mon"m '+%F'
done

Upvotes: 2

Related Questions