我试图在我的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