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

BashLogical Operators

Bash Problem Overview


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

JOBS=$(cat /proc/cpuinfo | grep processor | tail -1 | sed "s,^.*:.*\([0-9].*\)$,\1,")
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)?

Bash Solutions


Solution 1 - Bash

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

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

Solution 2 - Bash

Had a similar situation where I had to find the minimum out of several variables, and a somewhat different solution I found useful was 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 "$1" | head -n1
}
max() {
    # using sort's -r (reverse) option - using tail instead of head is also possible
    min ${1}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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionm-ricView Question on Stackoverflow
Solution 1 - BashmvdsView Answer on Stackoverflow
Solution 2 - BashArnon ZilcaView Answer on Stackoverflow