E T*_*E T 64 unix bash shell terminal ubuntu
我正在尝试bash script在我的Ubuntu机器上运行,它给了我一个错误:
功能未找到
为了测试,我创建了以下脚本,它可以在我的笔记本电脑上正常工作但不能在我的桌面上工 任何想法为什么?如果相关,我的笔记本电脑是mac.
#!/bin/bash
function sayIt {
echo "hello world"
}
sayIt
Run Code Online (Sandbox Code Playgroud)
这会在我的笔记本电脑上返回"hello world",但在我的桌面上会返回:
run.sh:3:找不到函数hello world run.sh:5:语法错误:"}"意外
Ned*_*ily 118
有可能在您的桌面上,您实际上并没有运行,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
Run Code Online (Sandbox Code Playgroud)
POSIX语法适用于:
$ more b.sh
#!/bin/sh
sayIt () {
echo "hello world"
}
sayIt
$ bash b.sh
hello world
$ dash b.sh
hello world
Run Code Online (Sandbox Code Playgroud)
Pra*_*shi 11
我遇到了同样的问题,然后我修改了语法,它对我有用.尝试删除关键字函数并在函数名后添加括号().
#!/bin/bash
sayIt()
{
echo "hello world"
}
sayIt
Run Code Online (Sandbox Code Playgroud)
Pio*_*das -5
函数名后面或者调用时不需要 () 吗?
function sayIt() { ...
}
sayIt()
Run Code Online (Sandbox Code Playgroud)
?:)
嗯,实际上,在我的 mac 上,它就像你粘贴的那样工作。
dtpwmbp:~ pwadas$ cat aa.sh
#!/bin/bash
function sayIt() {
echo "hello world"
}
sayIt
dtpwmbp:~ pwadas$ ./aa.sh
hello world
dtpwmbp:~ pwadas$
Run Code Online (Sandbox Code Playgroud)
比较 bash 版本,AFAIR 一些旧版本需要“()”。
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$
Run Code Online (Sandbox Code Playgroud)
还要比较两个 shell 上的 shopt 选项( man bash )的状态,也许其中一个打开或关闭了一些兼容语法?不带参数的“shopt”命令将列出支持的选项的状态。
某些 bash 脚本中使用的“function”关键字是什么?
| 归档时间: |
|
| 查看次数: |
50315 次 |
| 最近记录: |