我尝试匹配给定的字符串并将其与/ bin / sh脚本中的包版本匹配:
if test "x$version" = "x"; then
version="latest";
info "Version parameter not defined, assuming latest";
else
info "Version parameter defined: $version";
info "Matching version to package version"
case "$version" in
[^4.0.]*)
$package_version='1.0.1'
;;
[^4.1.]*)
$package_version='1.1.1'
;;
[^4.2.]*)
$package_version='1.2.6'
;;
*)
critical "Unable to match requested version to package version"
exit 1
;;
esac
fi
然而,当我运行它时,我收到一个错误:
23:38:47 +0000 INFO: Version parameter defined: 4.0.0
23:38:47 +0000 INFO: Matching Puppet version to puppet-agent package version (See http://docs.puppetlabs.com/puppet/latest/reference/about_agent.html for more details)
23:38:47 +0000 CRIT: Unable to match requested puppet version to puppet-agent version - Check http://docs.puppetlabs.com/puppet/latest/reference/about_agent.html
23:38:47 +0000 CRIT: Please file a bug report at https://github.com/petems/puppet-install-shell/
23:38:47 +0000 CRIT:
23:38:47 +0000 CRIT: Version: 4.0.0
我在剧本的另一部分使用了同样的正则表达式,它似乎在那里工作:
if test "$version" = 'latest'; then
apt-get install -y puppet-common puppet
else
case "$version" in
[^2.7.]*)
info "2.7.* Puppet deb package tied to Facter < 2.0.0, specifying Facter 1.7.4"
apt-get install -y puppet-common=$version-1puppetlabs1 puppet=$version-1puppetlabs1 facter=1.7.4-1puppetlabs1 --force-yes
;;
*)
apt-get install -y puppet-common=$version-1puppetlabs1 puppet=$version-1puppetlabs1 --force-yes
;;
esac
fi
我错过了什么?
该脚本的完整版本位于:https://github.com/petems/puppet-install-shell/blob/fix_puppet_agent_install/install_puppet_agent.sh
答案 0 :(得分:3)
case ... esac
使用(glob-style) patterns,而不是正则表达式(虽然两者之间存在远距离关系,但存在根本差异)。
sh
脚本中获得真正的正则表达式匹配,您必须将expr
与:
一起使用,尽管此处可能不需要它。 要测试前缀匹配,请在<prefix>*
分支中使用case
- 案例分支始终与整个匹配争论 - 不需要锚定(哪种模式不支持)。
[^4.0.]
与[^.04]
相同 - 即否定字符类:它匹配一个字符它既不是.
也不是0
,也不是4
。当将分配给POSIX shell脚本中的变量时,请不使用$
。
把它们放在一起:
#/bin/sh
if [ "$version" = "" ]; then
version="latest";
info "Version parameter not defined, assuming latest"
else
info "Version parameter defined: $version";
info "Matching version to package version"
case "$version" in
4.0.*)
package_version='1.0.1'
;;
4.1.*)
package_version='1.1.1'
;;
4.2.*)
package_version='1.2.6'
;;
*)
critical "Unable to match requested version to package version"
exit 1
;;
esac
fi