RSS Feed Share on Twitter

Buy this tutorial as a PDF for only $5!

All Shell Scripting Tips

30 Jan 2019

1st, 2nd, 3rd

Ordinal Numbers

Sometimes it is useful to write a number not as "1", "2" or "3", but as "1st", "2nd" or "3rd". These are known as Ordinal Numbers, and certainly in English (which is the only language this particular tip addresses), it's a bit odd, because we've got "th", "st", "nd" and "rd" endings, depending on the number.

The rule isn't quite as simple as it first looks, because it doesn't just depend on the final digit; the teens (and numbers ending in teens, such as 112, 213, 314) all end in "th" regardless of the final digit.

This simple function deals with these issues. The regular expressions in the case statement deal with:

  • *1[0-9] — any number ending in a 1, followed by any single digit. These are the numbers which are, or end with, a number between 10-19 inclusive. These will be ended with "th".
  • *[04-9] — the second part of the first case clause looks for any number ending in either 0, or the digits between 4 and 9 inclusive. These also end in "th".
  • *1 — any other number, ending in 1. This gets "st" appended to it. 1st, 21st, 31st, and so on (but not 11st).
  • *2 — any other number, ending in 2. This gets "nd" appended to it. 2nd, 22nd, 32nd, etc, but not 12nd.
  • *3 — any other number, ending in 3. This gets "rd" appended to it. 3rd, 23rd, 33rd, etc, but not 13rd.

Note: The pipe (|) between the first two expressions (*1[0-9] | *[04-9]) mean that either of those patterns being matched will result in "th".

Click here to download this script


function ordinal () {
  case "$1" in
    *1[0-9] | *[04-9]) echo "$1"th;;
    *1) echo "$1"st;;
    *2) echo "$1"nd;;
    *3) echo "$1"rd;;

  echo "$x is $(ordinal $x)"

When you run this script, you should get this result (where the final 8 are random numbers, from the magical "$RANDOM" variable).:

1 is 1st
2 is 2nd
3 is 3rd
4 is 4th
5 is 5th
6 is 6th
7 is 7th
8 is 8th
9 is 9th
10 is 10th
11 is 11th
12 is 12th
13 is 13th
14 is 14th
15 is 15th
16 is 16th
17 is 17th
18 is 18th
19 is 19th
20 is 20th
21 is 21st
22 is 22nd
23 is 23rd
24 is 24th
25 is 25th
100 is 100th
101 is 101st
102 is 102nd
19408 is 19408th
27557 is 27557th
23093 is 23093rd
23592 is 23592nd
324 is 324th
17637 is 17637th
12400 is 12400th
10604 is 10604th

I am sure you will find lots of places where this short little function is really worth including to make the output from a script more user-friendly.



Books and eBooks


You can mail me with this form. If you expect a reply, please ensure that the address you specify is valid. Don't forget to include the simple addition question at the end of the form, to prove that you are a real person!

You can buy the content of this Shell Scripting Tutorial as a PDF!