【问题标题】:The function definitions in shell use dash [duplicate]shell中的函数定义使用破折号[重复]
【发布时间】:2016-08-17 03:53:43
【问题描述】:

以下代码:

#!/bin/bash

function me-test()
{
        echo 'test'
}

me-test

下面的执行方法不正确:

#sh 1.sh
1.sh: line 6: `me-test': not a valid identifier

但是下面的执行方法是正确的:

#./1.sh
test

在其他编程语言中,不能使用破折号来定义函数,例如python。

为什么shell会这样?

【问题讨论】:

  • 另外,function 语法不是标准的,可能不适用于所有 posix 兼容的 shell。

标签: bash shell sh


【解决方案1】:

sh 1.sh 将脚本作为Bourne Shell 脚本运行,./1.sh 将其作为bash 脚本运行,因为您的行#!/bin/bash(这称为shebang,它告诉shell 使用哪个解释器) 调用 bash 解释器来运行脚本。 bash 允许在函数名中使用连字符,但 Bourne Shell 不允许。两者是非常相似但不同的编程语言。

如果您将#!/bin/bash 更改为#!/bin/sh,则每次运行程序时都会出错。

【讨论】:

  • 我知道,我想知道为什么“bash”可以而“sh”不能
  • ^^ 因为它们是不同的。
  • @anishsane 是正确的。
  • sh 几乎可以肯定是您的系统用作其 POSIX 兼容 shell 的任何 shell,而不是实际的 Bourne shell。如果该 shell 恰好是 bashbash 在模拟 POSIX 标准时会尝试更严格一些。
猜你喜欢
  • 2014-09-12
  • 2023-03-20
  • 1970-01-01
  • 2016-05-02
  • 1970-01-01
  • 2015-05-01
  • 2020-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多