POSIX and Hyphens: No Guarantee
According to the POSIX standard, a function name must be a valid name and a name can consist of:
3.231 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.
Additionally, an alias must be a valid alias name, which can consist of:
3.10 Alias Name
In the shell command language, a word consisting solely of underscores,
digits, and alphabetics from the portable character set and any of the
following characters: '!', '%', ',', '@'.
Implementations may allow other characters within alias names as an
extension. (Emphasis mine.)
A hyphen is not listed among the characters that must be allowed in either case. So, if they are used, portability is not guaranteed.
Examples of Shells That Do Not Support Hyphens
dash
is the default shell (/bin/sh
) on the debian-ubuntu family and it does not support hyphens in function names:
$ a-b() { date; }
dash: 1: Syntax error: Bad function name
Interestingly enough, it does support hyphens in aliases, though, as noted above, this is an implementation characteristic, not a requirement:
$ a_b() { printf "hello %s\n" "$1"; }
$ alias a-b='a_b'
$ a-b world
hello world
The busybox shell (only the ash based one) also does not support hyphens in function names:
$ a-b() { date; }
-sh: Syntax error: Bad function name
Summary of Hyphen Support by Shell
The following shells are known to support hyphens in function names:
- pdksh and derivatives, bash, zsh
- some ash derivatives such as the sh of FreeBSD (since 2010) or NetBSD (since 2016.
- busybox sh when the selected shell at compile time is
hush
instead of ash
.
- csh and tcsh (in their aliases, those shells have no function support). Those shells have a radically different syntax anyway, so there's no hope to have cross shell compatibility with those.
- rc and derivatives (again with a radically different syntax)
- fish (again with a radically different syntax)
The following shells are known not to support hyphens in function names:
- the Bourne shell and derivatives such as ksh88 and bosh (in the Bourne shell, functions and variables shared the same namespace, you couldn't have a variable and a function by the same name).
- ksh93, yash, the original ash and some of its derivatives (busybox ash (the default choice for sh), dash)
Conclusions
- Hyphens are non-standard. Stay away from them if you want cross-shell compatibility.
- Use underscores instead of hyphens: underscores are accepted everywhere.