我在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.
我正在尝试了解如何解决这些警告。我知道为了修复[[ ]]
我需要它切换到[ ]
但是由于globs而出现错误。另外,我应该如何更换=~
运算符?
当你写#!/bin/sh
时,你不应该使用像[[
这样的 bash 特定功能。但是您不需要将[[
更改为[
或类似的东西;只需将社邦线更改为#!/bin/bash
即可。然后,您可以使用所有您喜欢的bash功能。
在 posix 中使用grep
和sed
。
# use grep -q to match with regex
if printf "%sn" "$host" | grep -q '(git|ssh|http(s))etc. etc. etc.'; then
# use sed to extract part of the string matching regex
d=$(printf "%sn" "$host" | sed 's/(g|ssh|http(s))etc. etc. etc./2/')
if printf "%sn" "$d" | grep -q github; then
return
fi
fi
找出正确的正则表达式留给其他人。
您可以尝试使用参数扩展来解析不同的部分,尽管这会变得有点乏味。(链接指向 Bash 手册;Bash 支持的扩展中只有少数是 POSIX。
假设输入是一个有效的、格式正确的 URL(可能是保证的,也可能不是保证的(,也许可以尝试
host=$1
tail=${1#*://*/}
case $tail in "$host") tail=${host#*/};; esac
case ${host%/$tail} in
*github.com) return ;;
esac
die "Current repository is not stored in Github."
(当然,我们假设这是在return
有意义的上下文中,并且die
是单独定义的,就像我们必须在原始代码中假设的那样(。
这比你提出的正则表达式简单得多,并且绝对没有涵盖正则表达式能够处理的所有字符串;但如果我们可以假设 URL 已经经过了某种验证(即,如果它是git remote
的输出,假设用户已经通过其他方式验证它是相当安全的(。