gpt4 book ai didi

Bash script error : "function: not found". 为什么会出现这个?

转载 作者:行者123 更新时间:2023-11-29 08:40:03 26 4
gpt4 key购买 nike

我试图在我的 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 下运行,而是在 dash 或其他一些不识别 function< 的 POSIX 兼容 shell 下运行 关键字。 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

关于Bash script error : "function: not found". 为什么会出现这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12468889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com