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

前端之家收集整理的这篇文章主要介绍了Bash脚本错误:“function:not found” 为什么会出现?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在我的Ubuntu机器上运行一个bash脚本,它给我一个错误

function not found

为了测试,我创建了以下脚本,它在我的笔记本电脑上正常工作,但不在我的桌面上。任何想法为什么?我的笔记本电脑是一个mac,如果这是相关的。

  1. #!/bin/bash
  2.  
  3. function sayIt {
  4. echo "hello world"
  5. }
  6.  
  7. sayIt

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

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

任何帮助将不胜感激。

有可能在你的桌面上,你实际上不是在bash下运行,而是破折号或一些其他POSIX兼容的外壳,不能识别功能关键字。 function关键字是一个bashism,一个bash扩展。 POSIX语法不使用函数,并强制使用括号。
  1. $ more a.sh
  2. #!/bin/sh
  3.  
  4. function sayIt {
  5. echo "hello world"
  6. }
  7.  
  8. sayIt
  9. $ bash a.sh
  10. hello world
  11. $ dash a.sh
  12. a.sh: 3: function: not found
  13. hello world
  14. a.sh: 5: Syntax error: "}" unexpected

POSIX语法适用于以下两种情况:

  1. $ more b.sh
  2. #!/bin/sh
  3.  
  4. sayIt () {
  5. echo "hello world"
  6. }
  7.  
  8. sayIt
  9. $ bash b.sh
  10. hello world
  11. $ dash b.sh
  12. hello world

猜你在找的Bash相关文章