0

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 '16 at 18:38
  • 1
    No, there is no pre-defined minimum. But you should read stackoverflow.com/q/21452752/2350426 – user79743 Jan 10 '16 at 19:36
1

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' "$@"
}
| improve this answer | |
-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)
| improve this answer | |
  • 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

Not the answer you're looking for? Browse other questions tagged or ask your own question.