shell - Mac OSx 终端 : "not a valid identifier" on function definition

标签 shell sh zsh

我有一个 bash 脚本,我在其中定义了以下函数,

function start-if-exists()
{
    if [ "`docker container ls -a|grep $1`" ]; then
        echo "Container $1 exists. Starting $1..."
        return `docker start $1`
    else
        echo "Container $1 doesn't exists."
        return ""
    fi
}

直接在终端(zsh)中执行上述功能时,我没有收到任何错误。但是,当我使用 sh 命令 (sh my_script.sh) 执行它时,出现以下错误。

my_script.sh: line 10: `start-if-exists': not a valid identifier

my_script.sh 是文件名。

我的脚本在 zsh 上运行但在 sh 上运行失败,我错过了什么?

最佳答案

/bin/shbash,但是,当以 /bin/sh 启动时,它以 POSIX 模式启动。根据 bash 手册页,在 POSIX 模式下:

  1. Function names must be valid shell `name's. That is, they may not contain characters other than letters, digits, and underscores, and may not start with a digit. Declaring a function with an invalid name causes a fatal syntax error in non-interactive shells.

有关如何解决此类问题的注释:

  • 在终端命令行,我执行了 /bin/sh --version 来查看有关它的信息。它打印出“GNU bash,版本 3.2.57(1)-release (x86_64-apple-darwin17)”。
  • 然后我使用命令 man bash 引用了 bash 手册页。由于它很长,您可能更愿意将副本保存到文件中并在您喜欢的文本编辑器中查看它。原始 man 输出包括陈旧的下划线和退格键。您可以通过执行 man bash | 获得没有这些的副本。 col -b > file.txt.
  • 在手册页中,我搜索了“sh”(作为一个完整的词,而不是对这些字母的原始搜索,因为它们作为许多不相关词的一部分出现)。这很快就引发了关于 bash 以“sh”开头时表现不同的讨论;它以 POSIX 模式启动。
  • 进一步搜索“POSIX”显示了 POSIX 模式下的不同之处。

关于shell - Mac OSx 终端 : "not a valid identifier" on function definition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53364885/

相关文章:

github - 想家: sync modified zsh themefiles

linux - 限制 grep 的输出

linux - Bash 脚本、Expect 和与远程 CLI 的接口(interface)

mysql - 通过shell脚本连接mysql数据库服务器

java - 基于maven构建生成CLASSPATH字符串

bash - 如何在 unix 环境中填充超过 1024 个字符的文件?

bash - 是 shell : command portable?

bash - Z Shell 启动时出现错误(如 Powerline 9k 主题所示)

linux - 关于 PID Shell 脚本

linux - 将子文件夹重命名为父文件夹,删除 'extra' 文件夹