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

ves*_*sii 3 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."
Run Code Online (Sandbox Code Playgroud)

我想学习如何编写更好的 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.
Run Code Online (Sandbox Code Playgroud)

我正在尝试了解如何解决这些警告。我知道为了解决这个问题,[[ ]]我需要将其切换到[ ],但随后由于全局原因我收到了错误。另外我应该如何更换=~操作员?

Joh*_*ica 6

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