Ubuntu – Why are numeric function names not allowed

bashcommand linedash-shellksh

Consider the following:

$ ksh -c '1(){ echo hi;};1'
ksh: 1: invalid function name
$ dash -c '1(){ echo hi;};1'
dash: 1: Syntax error: Bad function name
$ bash -c '1(){ echo hi;};1'
bash: `1': not a valid identifier
bash: 1: command not found
$ mksh -c '1(){ echo hi;};1'
hi

Basically, I was trying to declare functions 1 and 0 which would be shorthands for true and false, but as you can see I ran into problem with using numeric names in functions. Same behavior occurs with aliases and two-digit names.

Question is "why"? Is it mandated by POSIX? or just a quirk of bourne-like shells?

See also related question to this one.

Best Answer

POSIX says:

2.9.5 Function Definition Command

A function is a user-defined name that is used as a simple command to call a compound command with new positional parameters. A function is defined with a "function definition command".

The format of a function definition command is as follows:

 fname ( ) compound-command [io-redirect ...]

The function is named fname; the application shall ensure that it is a name (see XBD Name) and that it is not the name of a special built-in utility. An implementation may allow other characters in a function name as an extension. The implementation shall maintain separate name spaces for functions and variables.

And:

3.235 Name

In the shell command language, a word consisting solely of underscores, digits, and alphabetics from the portable character set. The first character of a name is not a digit.

Note: The Portable Character Set is defined in detail in Portable Character Set.

So a word beginning with a digit cannot be a function name.