将 bash =~ 运算符更改为 sh 兼容参数

Vla*_*159 2 regex bash grep glob sh

所以我在coreos中运行一个bash脚本,因此我没有/bin/bash但是我有/bin/sh。现在 sh 一直很好,直到我使用别人的 bash 脚本并且他们有以下行。

 if [[ "$file" =~ ^https?:// ]]; then
Run Code Online (Sandbox Code Playgroud)

我的操作系统sh: =~: unknown operand现在抱怨我认为这意味着操作~=符与 sh 不兼容,但必须有其他方法来执行此表单查看所以我发现这~=是某种类型的正则表达式运算符。我的问题是这样我可以~=用什么来代替吗?注意:我的机器上有 grep。

Ini*_*ian 5

grep在我的机器上

按照上面的行,您可以使用 if 语句编写一个简单的条件作为

if echo "$file" | grep -Eq "^https?://"; then
    printf 'regex matches\n'
fi
Run Code Online (Sandbox Code Playgroud)

正则表达式匹配grep使用 ERE(扩展正则表达式),它在您安装的任何POSIX 兼容grep版本中都可用。在-q刚刚抑制打印的正常标准输出,但只是返回退出代码知道,如果匹配成功。

即使你的某些包grep没有-E允许,也只需使用基本的正则表达式支持,但剥夺?其特殊值并按字面意思传递

if echo "$file" | grep -q "^https\?://"; then
Run Code Online (Sandbox Code Playgroud)