How to get current month name in bash script

You can use the date(1) command.

For example:

date +%b

The strftime(3) manual (man 3 strftime), if installed on your system, will list all formatting strings that may be used with the date utility or the %(...)T format strings with printf. The manual of the date command may also contain the supported formatting strings.

To use one of them, for example %b ("the locale's abbreviated month name.") or %B ("the locale's full month name"), you use the + option for date:

$ date +%B
December

$ date +%b
Dec

$ date +'%B is abbreviated as "%b"'
December is abbreviated as "Dec"

Or, with printf (in ksh93 or bash 4.3+):

$ printf '%(%B)T\n'
December

$ printf '%(%b)T\n'
Dec

$ printf '%(%B is abbreviated as "%b")T\n'
December is abbreviated as "Dec"

To get a lowercased abbreviated month in bash (if your locale does not always provide lower-case names of months):

$ month=$( date +%b )
$ printf 'It is %s\n' "${month,,}"
It is dec

The parameter expansion ${parameter,,pattern} will modify the case of $parameter wherever pattern matches. In ${m,,}, the pattern matches everywhere, so the whole string in $m is lower-cased.

Or like in ksh, declare the variable as lower case beforehand with:

typeset -l month

With bash's printf, you may automatically insert the generated string in a scalar variable¹ using -v:

$ printf -v month '%(%b)T'
$ printf 'It is %s\n' "${month,,}"
It is dec

¹ or the element of key 0 of an array or associative array variable

Tags:

Bash

Date