Bash 脚本错误: “ function: not found”。为什么会出现这个错误?

我试图在我的 Ubuntu 机器上运行一个 bash script,它给了我一个错误:

未找到功能

为了进行测试,我创建了以下脚本,它可以在我的笔记本电脑上正常工作,但是在我的桌面上就不行了。知道为什么吗?如果有必要的话,我的笔记本电脑是苹果电脑。

#!/bin/bash


function sayIt {
echo "hello world"
}


sayIt

它在我的笔记本电脑上返回“ hello world”,但在我的桌面上返回:

函数未找到 hello world run.sh: 5: 语法错误: 出乎意料

81412 次浏览

Doesn't it require () after function name, or at the call?

function sayIt() { ...
}


sayIt()

? :)

Hmm, actually, on MY mac, it works just as you pasted..

dtpwmbp:~ pwadas$ cat aa.sh
#!/bin/bash


function sayIt() {
echo "hello world"
}


sayIt


dtpwmbp:~ pwadas$ ./aa.sh
hello world
dtpwmbp:~ pwadas$

Compare bash version, AFAIR some older version required "()"s.

dtpwmbp:~ pwadas$ bash --version
GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin12)
Copyright (C) 2007 Free Software Foundation, Inc.
dtpwmbp:~ pwadas$

Also compare state of shopt options ( man bash ), on both shells, maybe one of them have some compat syntax turned on or off ? "shopt" command without args will list state of options supported.

What is the 'function' keyword used in some bash scripts?

Chances are that on your desktop you are not actually running under bash but rather dash or some other POSIX-compliant shell that does not recognize the function keyword. The function keyword is a bashism, a bash extension. POSIX syntax does not use function and mandates the use of parenthesis.

$ more a.sh
#!/bin/sh


function sayIt {
echo "hello world"
}


sayIt
$ bash a.sh
hello world
$ dash a.sh
a.sh: 3: function: not found
hello world
a.sh: 5: Syntax error: "}" unexpected

The POSIX-syntax works in both:

$ more b.sh
#!/bin/sh


sayIt () {
echo "hello world"
}


sayIt
$ bash b.sh
hello world
$ dash b.sh
hello world

I faced the same problem, I then modified the syntax and it worked for me. Try to remove the keyword function and add brackets () after the function name.

#!/bin/bash


sayIt()
{
echo "hello world"
}


sayIt

ls -la /bin/sh

check the sym link where it point to bash or dash

For me, I just edited the bash profile and forgot to restart my terminal session.