我的bash版本是:
bash --version
GNU bash, version 4.2.45(1)-release (x86_64-pc-linux-gnu)
Run Code Online (Sandbox Code Playgroud)
如果我做原型功能
#!/bin/bash
function f()
{
echo "hello" $1
}
f "world"
Run Code Online (Sandbox Code Playgroud)
我明白了 Syntax error: "(" unexpected
这是为什么?
shopt的输出是:
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
Run Code Online (Sandbox Code Playgroud)
您的版本bash 确实接受该function关键字.问题是你没有运行你的脚本bash.
如果我用dash foo.bash或运行脚本sh foo.bash(在我的系统上/bin/sh是一个符号链接),我会得到同样的错误dash.
dash无法识别function语法.
该#!/bin/bash行会导致您的脚本被bash解释 - 但前提是您直接调用它,而不是将其提供给其他shell.
而不是调用shell并将脚本名称作为参数传递给它:
sh foo.bash
Run Code Online (Sandbox Code Playgroud)
只是直接调用你的脚本:
foo.bash (or ./foo.bash)
Run Code Online (Sandbox Code Playgroud)