bash - 修复小型 Bash 程序中的 POSIX sh 警告

标签 bash sh

我在 Bash 中编写了以下代码:

#!/bin/sh

host=$1
regex="^(((git|ssh|http(s)?)|(git@[\w\.]+))(:(\/\/)?)([A-Za-z0-9.@:_/-]+)\.com)(.*)"
if [[ "$host" =~ $regex  ]]; then
    d=${BASH_REMATCH[1]}
    if [[ "$d" = *github* ]]; then
        return
    fi
fi
die "Current repository is not stored in Github."

我想学习如何编写更好的 Bash 代码,所以我使用了 shellcheck.net。

Line 5:
if [[ "$host" =~ $regex  ]]; then
   ^-- SC2039: In POSIX sh, [[ ]] is undefined.

Line 6:
    d=${BASH_REMATCH[1]}
      ^-- SC2039: In POSIX sh, array references are undefined.

Line 7:
    if [[ "$d" = *github* ]]; then
       ^-- SC2039: In POSIX sh, [[ ]] is undefined.

我正在尝试了解如何修复这些警告。我知道为了修复 [[ ]] 我需要将其切换到 [ ] 但随后由于 glob 出现错误。另外,我应该如何替换 =~ 运算符?

最佳答案

当您编写 #!/bin/sh 时,您不应该使用像 [[ 这样的特定于 bash 的功能。但是您不需要将 [[ 更改为 [ 或类似的东西;只需将 shebang 行更改为 #!/bin/bash。然后您可以使用所有您喜欢的 bash 功能。

关于bash - 修复小型 Bash 程序中的 POSIX sh 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59553587/

相关文章:

bash - 在 bash 脚本 : next occurrence of 3pm 中使用日期命令

bash - 如何在 bash for 循环中从更大的文件列表中复制/列出具有编号名称模式的文件?

ios - Facebook iOS SDK - 如何为 Xcode 4.3 构建静态库?

linux - 如何让 bash 代码处理文件夹和子文件夹中的所有文件?

shell - 将 SFTP 输出捕获到变量时出现问题

bash - 为什么在同一行变量赋值后 shell 内置冒号命令 ":"会导致分配空字符串值?

sh : 1 file not found error with system() command? 的原因在 StackOverflow 中尝试了可能的解决方案(如下所列)但失败

python - 获取两个提交或分支之间更改文件的列表

python - 无法在Python中使用子流程模块(无此类文件)

linux - CentOS中bash启动时如何自动设置别名?