ynn
ynn

Reputation: 4815

bash function definition gives syntax error

I cannot define a bash function only for specific names and when I use <function name>() syntax and when I try to define it in the current shell (i.e. not in a subshell).

$ cat -n test.sh 
1   function f { true; }
2   
3   f() { true; }
4   
5   function make { true; }
6   
7   make() { true; }

$ function f { true; } && f() { true; } #OK

$ function make { true; } && make() { true; } #NG
bash: syntax error near unexpected token `(`

$ bash test.sh #OK

$ source test.sh #NG
bash: test.sh: line 7: syntax error near unexpected token `(`
bash: test.sh: line 7: `make() { true; }'

What's happening here? Is this an expected behavior? I believe, at least, this is not syntax error near unexpected token `(' as the error message suggests.


Environment

$ bash --version
GNU bash, version 5.0.16(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2019 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Upvotes: 5

Views: 958

Answers (2)

ynn
ynn

Reputation: 4815

The cause of the problem is described in John's answer. I'm writing this answer to give solutions how to avoid the problem.

Solution 1

First undefine the alias and then define the function. Writing like this every time (for safety) seems troublesome, but this is a POSIX-compliant way.

unalias make
make() { true; }

Solution 2

Or use another form of function definitions. This is simple but not POSIX-compliant.

function make { true; }
#or
function make() { true; }

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361565

You have some sort of make alias that's getting triggered. I can reproduce this if I create an alias with purposeful syntax errors:

$ alias make='@)$*)@'
$ make() { true; }
bash: syntax error near unexpected token `)'

Aliases only execute interactively. They're not active inside scripts, which explains why this only happens when you run the command by hand or with source.

Upvotes: 6

Related Questions