10

I want to map, for example, 4 to 'Apr' (3 character abbrev of the name of the month)

3 Answers 3

21

Try this :

MONTHS=(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)

echo ${MONTHS[3]}

Or as per @potong's suggestion (to have a 1-1 correspondence between month number and index)

MONTHS=(ZERO Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)

echo ${MONTHS[4]}
2
  • I pick this answer because it is simpler Apr 11, 2012 at 1:39
  • 7
    Maybe MONTHS=( dummy Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec) would be more intuitive as then 4 maps to Apr.
    – potong
    Apr 11, 2012 at 5:05
15
#! /bin/bash
case $1 in 
  [1-9]|1[0-2])     date -d "$1/01" +%b ;;
  *)            ;  exit 1
esac
0
7

A locale-sensitive result can be gained like this; put the number into the month-position of the date, passed as date to be output to date, and choose an arbitrary year and day (keep away from the 50ies and the far future, and avoid days much greater than 20). It hasn't to be the actual year:

i=10; date -d 2012/${i}/01 +%b

Here, with locale de_DE, I get as result:

Okt

(I didn't choose April, because it is the default for date to take the current month, so with a bad formatted -d -date, you get April, even if i=10. I know it, because I experienced it. And furthermore: The german name for April is April, so it wouldn't serve well as example for the finer details, which follow just now:)

i=10; LC_ALL=C date -d 2012/${i}/01 +%b

this reveals the month in an international standard style.

The advantage of the solution is, that it will survive revolutions, which rename the months to Brumaire, Obamer or internationalization attemps (Mär, Mai, Okt, Dez in German, i.e.).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.