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?

4
  • 1
    stackoverflow.com/questions/11025114/… Commented Sep 27, 2019 at 23:35
  • 2
    @JoshLee: That's an issue, but it looks like something else is going wrong before parsing reaches that point. Commented Sep 27, 2019 at 23:38
  • That said, I can't reproduce the reported problem. The ! causes problems, but naming a function df seems to work fine. Commented Sep 27, 2019 at 23:41
  • 2
    To diagnose: type -a df Commented Sep 28, 2019 at 3:33

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.