我的 Bash 脚本接受版本号参数,格式如下:#.#.#.#.dev
或 #.#.#.#.prod
,其中 #
可以是任意数字,例如:3.6.212.0.dev
。
我想验证参数的格式是否正确(包含所有用点分隔的 4 个数字,并在最后包含 .prod
或 .dev
)。
我不知道如何实现这一点,到目前为止我已经尝试过:
re='^[0-9]+$'
if ! [[ $1 =~ $re ]] ; then
echo "error: Incorrect version specified; must be in the format of #.#.#.#.env" >&2; exit 1
fi
最佳答案
你可以使用
re='^([0-9]+\.){4}(dev|prod)$'
if ! [[ "$1" =~ $re ]] ; then
echo "error: Incorrect version specified; must be in the format of #.#.#.#.env" >&2; exit 1
fi
查看Bash demo online .
^([0-9]+\.){4}(dev|prod)$
是符合 POSIX ERE 的模式,匹配:
^
- 字符串开头([0-9]+\.){4}
- 出现四次一个或多个数字和一个点(dev|prod)
-dev
或prod
子字符串$
- 字符串结尾。
关于regex - 如何在 Bash 中测试变量是否符合指定格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66924239/