Getting Your Plurals Right

Problem

You want to use a plural noun when you have more than one of an object. But you don’t want to scatter if statements all through your code.

Solution

#!/usr/bin/env bash
# cookbook filename: pluralize
#
# A function to make words plural by adding an s
# when the value ($2) is != 1 or -1
# It only adds an 's'; it is not very smart.
#
function plural ()
{
    if [ $2 -eq 1 -o $2 -eq -1 ]
    then
        echo ${1}
    else
        echo ${1}s
    fi
}

while read num name
do
    echo $num $(plural "$name" $num)
done

Discussion

The function, though only set to handle the simple addition of an s, will do fine for many nouns. The function doesn’t do any error checking of the number or contents of the arguments. If you wanted to use this script in a serious application, you might want to add those kinds of checks.

We put the name in quotes when we call the plural function in case there are embedded blanks in the name. It did, after all, come from the read statement, and the last variable on a read statement gets all the remaining text from the input line. You can see that in the following example.

We put the solution script into a file named pluralize and ran it against the following data:

$ cat input.file
1 hen
2 duck
3 squawking goose
4 limerick oyster
5 corpulent porpoise

$ ./pluralize < input.file
1 hen
2 ducks
3 squawking gooses
4 limerick oysters
5 corpulent porpoises
$

“Gooses” isn’t correct English, but the script did what was intended. If you like the C-like syntax better, you could write the if statement like this:

if (( $2 == 1 || $2 == -1 ))

The square bracket (i.e., the test built-in) is the older form, more common across the various versions of bash, but either should work. Use whichever form’s syntax is easiest for you to remember.

We don’t expect you would keep a file like pluralize around, but the plural function might be handy to have as part of a larger scripting project. Then whenever you report on the count of something you could use the plural function as part of the reference, as shown in the while loop above.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.113.188