bash 如何简单地在bash中计算两个变量的最小值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10415064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 22:01:07  来源:igfitidea点击:

how to calculate the minimum of two variables simply in bash?

bashlogical-operators

提问by m-ric

I have a bash script checking the number of CPUs on the platform to efficiently use -joption for make, repo, etc. I use this:

我有一个 bash 脚本检查平台上的 CPU 数量以有效地使用-jmake、repo 等选项。我使用这个:

JOBS=$(cat /proc/cpuinfo | grep processor | tail -1 | sed "s,^.*:.*\([0-9].*\)$,,")
echo -e "4\n$JOBS" | sort -r | tail -1

It works fine. But, I am wondering if there was any built-in function which does the same thing (i.e. calculating the minimum, or maximum)?

它工作正常。但是,我想知道是否有任何内置函数可以做同样的事情(即计算最小值或最大值)?

回答by mvds

If you mean to get MAX(4,$JOBS), use this:

如果您想获取MAX(4,$JOBS),请使用以下命令:

echo $((JOBS>4 ? JOBS : 4))

回答by Arnon Zilca

Had a similar situation where I had to find the minimum out of severalvariables, and a somewhat different solution I found useful was sort

有一个类似的情况,我必须从几个变量中找到最小值,我发现有用的一个有点不同的解决方案是sort

#!/bin/bash

min_number() {
    printf "%s\n" "$@" | sort -g | head -n1
}

v1=3
v2=2
v3=5
v4=1

min="$(min_number $v1 $v2 $v3 $v4)"

I guess It's not the most efficient trick, but for a small constant number of variables, it shouldn't matter much - and it's more readable than nesting ternary operators.

我想这不是最有效的技巧,但对于少量恒定数量的变量,它应该没有太大关系 - 它比嵌套三元运算符更具可读性。



EDIT: Referring Nick's great comment - this method can be expanded to any type of sort usage:

编辑:参考尼克的精彩评论 - 此方法可以扩展到任何类型的排序用法:

#!/bin/bash

min() {
    printf "%s\n" "${@:2}" | sort "" | head -n1
}
max() {
    # using sort's -r (reverse) option - using tail instead of head is also possible
    min r ${@:2}
}

min -g 3 2 5 1
max -g 1.5 5.2 2.5 1.2 5.7
min -h 25M 13G 99K 1098M
max -d "Lorem" "ipsum" "dolor" "sit" "amet"
min -M "OCT" "APR" "SEP" "FEB" "JUL"