Mar*_*ppi 3 regex bash dash-shell
出于兼容性原因,我正在移动一个bash脚本.是否有POSIX/Dash替代以下比较?
COMPARE_TO="^(lp:~?|https?://|svn://|svn\+ssh://|bzr://|bzr\+ssh://|git://|ssh://)"
if [[ $COMPARE =~ $COMPARE_TO ]]; then
echo "WE ARE COMPARED!"
fi
Run Code Online (Sandbox Code Playgroud)
你可以使用案例.它不使用正则表达式,但它与globs相比并不长
case $compare in
lp:*|http://*|https://*|svn://*|svn+ssh://*|bzr://*|bzr+ssh://*|git:/*|ssh://*)
echo "We are compared"
;;
esac
Run Code Online (Sandbox Code Playgroud)
另外,您应该避免使用所有大写变量名称,因为您可能会覆盖特殊的shell变量或环境变量.
dash 没有内置正则表达式比较,但您始终可以使用 grep:
if echo "$compare" | egrep -q "$compare_to"; then
...
Run Code Online (Sandbox Code Playgroud)
(请注意,我是第二个@geirha 关于 shell 中大写变量的注释。)