I need to convert some javascript calculations to bash, and I am wondering if there is an equivalent function of javascript Math.min()
in bash, bc or any other calculator in the shell?
-
How will the data be presented? Shell array? Separate variables ? A string - one with newline separators?– Jeff Schaller ♦Jan 10, 2016 at 18:38
-
1No, there is no pre-defined minimum. But you should read stackoverflow.com/q/21452752/2350426– user79743Jan 10, 2016 at 19:36
Add a comment
|
2 Answers
With POSIX shell:
min() {
min=$1
shift
for arg do
min=$((arg<min?arg:min))
done
printf '%s\n' "$min"
}
All shells but zsh
, ksh
and yash
do not support float numbers.
With POSIX toolchest:
min() {
awk 'BEGIN {
min = ARGV[1]
for(i = 2; i < ARGC; i++)
min = ARGV[i] < min ? ARGV[i] : min
print min
}' "$@"
}
And if you have perl
:
min() {
perl -MList::Util=min -le 'print min @ARGV' "$@"
}
or perl6
:
min() {
perl6 -e '@*ARGS.min.say' "$@"
}
Push your data to a file, then sort them up and get the first line.
#/bin/sh
echo $VAR1 > $FILE
echo $VAR2 >> $FILE
echo $VAR3 >> $FILE
RET=$(sort -n $FILE | sort -n)