【问题标题】:Bash bad substitution when trying to uppercase first letter尝试大写第一个字母时 Bash 错误替换
【发布时间】:2020-02-25 12:51:08
【问题描述】:

关于 Bash 中的 Bad substitution 错误,我头疼不已。考虑以下代码:

getApiName() {
    IFS='-' # hyphen (-) is set as delimiter
        read -ra array <<< "$1" # str is read into an array as tokens separated by IFS
        for i in "${array[@]}"; do # access each element of array
            output+=${i^} #set first letter to uppercase
        done
    IFS=' '
    echo ${output}
}

当我执行以下操作时:

getApiName "vl-date-picker"

我收到line 21: ${i^}: bad substitution

我不知道出了什么问题。 大家能帮帮我吗?

提前致谢。 问候

【问题讨论】:

  • 你确定你在 bash 上运行这个?
  • 是的,不过通过 npm 运行脚本
  • 我不了解 npm,但这适用于我的 bash。确保它是 bash 而不是 sh
  • @Homewrecker:echo $BASH_VERSION 在您的脚本中(而不是在您的命令行上)执行时会输出什么?

标签: bash


【解决方案1】:

一般性回答

我无法重现您的问题。我看到两个可能的原因:

  • 您使用的是非 bash shell。
    通过将命令 ps 添加到脚本并查看输出来检查这一点。如果输出中没有bash,那么您正在运行不同的东西。脚本开头的 shebang #! /bin/bash 有助于确保使用 bash,但不是保证。 ✱

  • 您有旧版本的 bash,不支持 ${i^}
    (例如 Mac OS X 上预装的 15 (!) 年前版本)

    您可以使用bash --version 检查您的 bash 版本。 ${i^} 是在 bash 4.0 中引入的,可以阅读 here(搜索 hh. There are new case-modifying word expansions)或 here

无论哪种方式,您都可以使用应该适用于所有 Posix shell 的不同命令。

如果你有sed的GNU版本(检查sed --version)这个命令可能是

getApiName() {
    printf %s "$1" | sed -E 's/(^|-+)(.)/\U\2/g'
}

Nmp 特定答案

documentation of npm-run-script 状态

运行脚本的实际 shell 取决于平台。默认情况下,在类 Unix 系统上是 /bin/sh 命令,在 Windows 上是 cmd.exe。 /bin/sh 所指的实际外壳也取决于系统。从 npm@5.1.0 开始,您可以使用 script-shell 配置自定义 shell。

因此,要解决您的问题,您只需配置 npm 以使用 bash

作为一种解决方法,您也可以直接在脚本中调用bash。最简单的方法是这里的文档:

bash -s -- "$@" <<"EOF"
    # your original script here
EOF

【讨论】:

  • 将 ps 添加到脚本中告诉我,尽管存在 shebang 行,但脚本以 sh 运行。 75493 ttys001 0:00.00 sh -c . ./scripts/updateReadme.sh。我将不得不弄清楚如何强制 NPM 使用 bash。
猜你喜欢
  • 1970-01-01
  • 2013-05-21
  • 1970-01-01
  • 2013-09-01
  • 2018-07-08
  • 2017-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多