如何解决bash 3.2 和 4.3 之间的区域设置更改破坏了浮点比较
Started by user User
Running as SYstem
Building in workspace /var/lib/jenkins/workspace/first_git_job
The recommended git tool is: NONE
No credentials specified
cloning the remote Git repository
cloning repository https://github.com/user/test2.git
> git init /var/lib/jenkins/workspace/first_git_job # timeout=10
Fetching upstream changes from https://github.com/user/test2.git
> git --version # timeout=10
> git --version # 'git version 2.17.1'
> git fetch --tags --progress -- https://github.com/user/test2.git +refs/heads/*:refs/remotes/origin/* # timeout=10
> git config remote.origin.url https://github.com/user/test2.git # timeout=10
> git config --add remote.origin.fetch +refs/heads/*:refs/remotes/origin/* # timeout=10
Avoid second fetch
> git rev-parse refs/remotes/origin/master^{commit} # timeout=10
> git rev-parse origin/master^{commit} # timeout=10
ERROR: Couldn't find any revision to build. Verify the repository and branch configuration for this job.
Finished: FAILURE
这是“为什么”它从 4.1 开始不起作用:
Within double brackets,the > and < string comparison operators now conform to the locale.
这太荒谬了。这是一个很好的旧 ASCII 数字字符串,整个世界都希望在字符串比较中句点 [.] 小于 [0-9]。我们在谈论哪个语言环境?
现在的挑战是如何在不使用自定义函数的情况下删除/替换这个神话般的语言环境,使 Bash 4.x 生成“yes”?
有很多使用自定义函数的解决方案,例如this elegant one using sort -V。然而,这个挑战是关于配置 Bash's undocumented locale feature 使其表现得好像它只知道 1970 年的 7 位 ASCII 字符集 - 句点小于数字。
解决方法
即使在 bash 3.2 中,所描述的做法也不能可靠地工作
观察:
[[ "2.0" < "10.0" ]] && echo "yes"
...在所有 bash 版本上为false,无论是否有所描述的语言环境更改。
无语言环境依赖性的本机实现
如果您真的想在没有外部工具的情况下在内部执行此操作以进行 bash,那么正确实现的最简单方法是对整数部分使用数字整数比较,然后对后面的数字进行字符串比较小数点。
冒着罗嗦的风险:
float_is_greater() {
local a_dec a_man b_dec b_man
a_dec=${1%%.*}; b_dec=${2%%.*}
a_man=${1#*.}; b_man=${2#*.}
(( ${a_dec:-0} > ${b_dec:-0} )) && return 0
(( ${b_dec:-0} > ${a_dec:-0} )) && return 1
[[ ${a_man} > ${b_man} ]] && return 0
return 1
}
float_is_greater 11.0 1.9 && echo yes
使用外部工具的 POSIX 兼容实现
也就是说,通常的做法是使用具有原生浮点数学支持的标准 POSIX 提供的工具。例如:
case $(echo '1.9 - 11.0' | bc) in
-*) echo '1.9 is less than 11.0';;
esac
...采用BashFAQ #22中给出的示例之一。
,我的脚本将“1.9”与 JDK 版本字符串“11.0.11”进行比较,我期望 ASCII 句点 [.] 小于 [0-9]。我的用例不是关于浮点比较,而是我的问题标题被 Charles 更改了。
我为我的用例找到了最简单的解决方案,即切换到使用 ASCII 排序顺序的单个 [:
$ echo $BASH_VERSION
4.3.11(1)-release
$ [ "1.9" \< "11.0.1" ] && echo "yes"
yes
$
Here is a more narrow focus question about [[ string1 < string2 ]] 继续讨论。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。