Home > Software design >  How do I select the smallest integer of 4 for use in bash script file
How do I select the smallest integer of 4 for use in bash script file

Time:05-18

So I've run into this problem. So I got these four integers

a={random integer} ; b={random integer} ; c={random integer} ; d={random integer}

and I want to select the smallest out of those four.

I have tried this but, however it didn't work.

(( a < b ? a : b ))

this output ether 1 or 2 but only for a and b.

Another thing I've tried is to use (( a < b ? a : b )) but also with (( c < d ? c : d )) and with a bunch of case statements and if statements, however that would ultimately be a lot slower and file size intensive than what's hopefully theoretically possible.

So in conclusion, how do I choose the lowest number of four integers?

CodePudding user response:

I don't know if this is what you're looking for, but:

a=5
b=6
c=4
d=7

e=$(echo -e "$a\n$b\n$c\n$d" | sort -n | head -n 1)

Works just fine if you only want to get the minimal value, and don't necessarily have to know which variable is it.


Generally I would say though that if you have that many variables that you need to compare to each other, it might be a sign to put them in an array. It's not necessarily the case here, but it might point to them being logically tied.

CodePudding user response:

A web search on bash find minimum of multiple variables (or comparable) will turn up several hits (eg, this, this, this) that will give you several ideas.

Setup:

a=3; b=-2; c=6; d=10

A few ideas:

$ printf "%s\n" $a $b $c $d | sort -n | head -1
-2

$ unset min; for i in $a $b $c $d; do [[ "$i" -le "${min:-$i}" ]] && min="$i"; done; echo $mim
-2

$ min=$a; for i in $b $c $d; do (( i<=min ? (min=i) : (min=min) )); done; echo $min
-2

$ echo $a $b $c $d | awk '{ min=$1; for (i=2;i<=NF;i  ) min=($i<min ? $i : min); print min}'
-2

CodePudding user response:

Try

declare -i min='a<b?a:b'
min='min<c?min:c'
min='min<d?min:d'
echo "$min"
  •  Tags:  
  • bash
  • Related