1

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?

aghast
  • 14,785
  • 3
  • 24
  • 56

1 Answers1

4

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
that other guy
  • 116,971
  • 11
  • 170
  • 194
  • I tried to verify this, in a different window, and realized you're entirely correct! I had been playing with df-as-alias before moving to df-as-function, and sure enough there was a legacy alias in the shell window where I was having the problem. Great catch, thanks! – aghast Sep 28 '19 at 19:04