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

我试图在我的Ubuntu机器上运行一个bash脚本,它给我一个错误

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

任何帮助将不胜感激。

有可能在你的桌面上,你实际上不是在bash下运行,而是破折号或一些其他POSIX兼容的外壳,不能识别功能关键字。 function关键字是一个bashism,一个bash扩展。 POSIX语法不使用函数,并强制使用括号。
$ 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

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...