I am using GNU bash, version 4.4.12(1)-release (x86_64-pc-linux-gnu)
.
I have the following lines in one of my startup files:
df() {
printf "Hello, world!\n"
}
When source that file, I get this error:
-bash: sh/interactive.sh: line 109: syntax error near unexpected token `('
-bash: sh/interactive.sh: line 109: `df() {'
However, if I change the function name from df
to dir
or ef
or anything_else
I don't get the error.
I'm assuming that df
is somehow a reserved word, but when I checked this list of reserved words in bash I couldn't find it. (And I don't think it deserves to be one, anyway!)
So, can anyone shed some light on this? Why does bash prohibit me from defining a shell function named df
?
This happens because you've previously defined an alias for this name. Aliases are simple string prefix substitutions, and therefore interfere with function definitions:
$ alias foo='foo --bar'
$ foo() { echo "Hello"; }
bash: syntax error near unexpected token `('
This is equivalent to (and fails with the same error as)
$ foo --bar() { echo "Hello"; }
bash: syntax error near unexpected token `('
To declare a function with a name that's been overridden with an alias, you can use the function
keyword:
$ alias foo='foo --bar'
$ function foo() { echo "Hello, $1"; }
$ foo
Hello, --bar