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

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


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

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


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/bashmin_number() {    printf "%s\n" "$@" | sort -g | head -n1}v1=3v2=2v3=5v4=1min="$(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/bashmin() {    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 1max -g 1.5 5.2 2.5 1.2 5.7min -h 25M 13G 99K 1098Mmax -d "Lorem" "ipsum" "dolor" "sit" "amet"min -M "OCT" "APR" "SEP" "FEB" "JUL"