fpghost
fpghost

Reputation: 2944

Why won't my version of bash accept function keyword?

My version of bash is:

bash --version
GNU bash, version 4.2.45(1)-release (x86_64-pc-linux-gnu)

If I do the prototype function

#!/bin/bash
function f()
{
echo "hello" $1
 }
 f "world"

I get Syntax error: "(" unexpected

Why is that?

Output of shopt is:

autocd          off
cdable_vars     off
cdspell         off
checkhash       off
checkjobs       off
checkwinsize    on
cmdhist         on
compat31        off
compat32        off
compat40        off
compat41        off
direxpand       off
dirspell        off
dotglob         off
execfail        off
expand_aliases  on
extdebug        off
extglob         on
extquote        on
failglob        off
force_fignore   on
globstar        off
gnu_errfmt      off
histappend      on
histreedit      off
histverify      off
hostcomplete    off
huponexit       off
interactive_comments    on
lastpipe        off
lithist         off
login_shell     off
mailwarn        off
no_empty_cmd_completion off
nocaseglob      off
nocasematch     off
nullglob        off
progcomp        on
promptvars      on
restricted_shell    off
shift_verbose   off
sourcepath      on
xpg_echo        off

Upvotes: 1

Views: 801

Answers (1)

Keith Thompson
Keith Thompson

Reputation: 263197

Your version of bash does accept the function keyword. The problem is that you're not running your script under bash.

I get the same error if I run the script with dash foo.bash or sh foo.bash (/bin/sh is a symlink to dash on my system).

dash doesn't recognize the function syntax.

The #!/bin/bash line causes your script to be interpreted by bash -- but only if you invoke it directly, not if you feed it to some other shell.

Rather than invoking a shell and passing your script name to it as an argument:

sh foo.bash

just invoke your script directly:

foo.bash (or ./foo.bash)

Upvotes: 6

Related Questions