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?
Asked
Active
Viewed 393 times
1

DisplayName
- 11,688
-
How will the data be presented? Shell array? Separate variables ? A string - one with newline separators? – Jeff Schaller Jan 10 '16 at 18:38
-
1No, there is no pre-defined minimum. But you should read http://stackoverflow.com/q/21452752/2350426 – Jan 10 '16 at 19:36
2 Answers
2
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' "$@"
}

cuonglm
- 153,898
-1
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)
-
We expect answers to be more comprehensive here. Please [edit] your answer and explain how exactly the OP can do what you suggest. As it stands, this is a comment, not an answer. – terdon Jan 10 '16 at 19:39