how to calculate the minimum of two variables simply in 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"

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

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