tech-userlevel archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: Weekday abbreviations in output of cal(1)



Am 30.06.20 um 11:38 schrieb Martin Husemann:
> On Tue, Jun 30, 2020 at 11:24:51AM +0200, Michael Siegel wrote:
>> Well, how would you use date(1) to return the number of days in any
>> given month, for example?
> 
> Good example, slightly complex but still close to cal|wc ;-)
> 
> Martin
> 
> --8<--
> #! /bin/sh
> 
> YEAR=2020
> MONTH=6
> 
> if [ $MONTH -lt 12 ]; then
>         next_year=$YEAR
>         next_month=$(( $MONTH + 1 ))
> else
>         next_year=$(( $YEAR + 1 ))
>         next_month=1
> fi
> 
> ms=$( date -d "${YEAR}-${MONTH}-1" '+%s' )
> ns=$( date -d "${next_year}-${next_month}-1" '+%s' )
> 
> diff=$(( $ns - $ms ))
> days=$(( $diff / 86400 ))
> 
> echo "${YEAR}-${MONTH} has ${days} days"

I see. That's pretty neat, and arguably better than parsing the output
of cal(1).

The simplest variant of doing it by parsing that output that I was able
to come up with is this:

  _get_days_in_month() {

    m="$1"
    y="$2"

    cal "$m" "$y" | sed '1,2 d' | wc -w | tr -d ' '
  }

This is actually POSIX-compliant, with the important caveat that POSIX
states cal(1) shall use STDOUT “to display the calendar, in an
unspecified format.”[1]


Michael

[1] https://pubs.opengroup.org/onlinepubs/9699919799/utilities/cal.html


Home | Main Index | Thread Index | Old Index