2012-09-18 197 views
47

我想我的Ubuntu机器上运行一个bash script和它给我一个错误:Bash脚本错误:“function:not found”。为什么会出现?

function not found

为了测试,我创建了下面的脚本,它工作在我的笔记本电脑却没有关于我的桌面罚款。任何想法为什么?我的笔记本电脑是一个mac,如果这是相关的。

#!/bin/bash 

function sayIt { 
    echo "hello world" 
} 

sayIt 

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

run.sh: 3: function not found hello world run.sh: 5: Syntax error: "}" unexpected

任何帮助将非常感激。

回答

-3

它是否需要()函数名称后,或在呼叫?

function sayIt() { ... 
} 

sayIt() 

? :)

嗯,其实,在我的Mac,它的工作原理就像你贴..

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

function sayIt() { 
    echo "hello world" 
} 

sayIt 

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

比较bash的版本,AFAIR需要一些旧版本的 “()” 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$ 

也比较禁用了javascript选项(男子bash)的状态,在两个炮弹,也许他们中的一个有一定COMPAT语法打开或关闭?不带参数的“shopt”命令将列出支持的选项状态。

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

+0

给了我一个:语法错误“(”意外 –

+0

可悲的是,我真的不知道为什么我对这个问题的答案downvoted:/ –

+0

您应该包括''在()函数的定义,但不当你调用函数 – Jacob

86

机会是您的桌面上,你实际上并没有bash下运行,而是dash或其他一些POSIX兼容的外壳,不承认function关键字。 function关键字是bashism,bash扩展名。 POSIX语法不使用function并强制使用括号。

$ 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 

的POSIX语法工作在两个:

$ more b.sh 
#!/bin/sh 

sayIt() { 
    echo "hello world" 
} 

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

https://wiki.ubuntu.com/DashAsBinSh –

+1

'功能'来自korn外壳,它在日期前bash。 – cdarke

+1

+1有这个确切的问题,但bash仍然会按预期执行。至少在你的解释中,我知道**为什么**和**如何**! :) – Zuul

6

我面临同样的问题,我再修改语法,它为我工作。尝试删除关键字功能添加括号()函数名后。

#!/bin/bash 

sayIt() 
{ 
    echo "hello world" 
} 

sayIt