Sergey
Sergey

Reputation: 49788

Calculate maximum argument passed to a bash script

I'm trying to calculate maximum argument passed to a bash script. Here's the code:

#!/bin/sh

max=$1

for var in "$@"
do
    if ($var>$max)
    then
        max=$var
    fi
done

echo $max

Here is what I get:

$ /bin/sh my_script 1 2 3
rgz: 11: 1: not found
rgz: 11: 2: not found
rgz: 11: 3: not found
1

What am I doing wrong?

Upvotes: 2

Views: 2342

Answers (3)

mondano
mondano

Reputation: 875

You can pipe the results to sort and find the maximum (the last item in the sorted list) with tail:

your stuff | sort -n | tail -1

May be this is not the computationally most efficient way to get the maximum, but gets the job done.

Upvotes: 0

Eve Freeman
Eve Freeman

Reputation: 33175

This is mine. Minor improvement...

#!/bin/bash

max="$1"
for v in "$@"
do
  [[ $v -gt $max ]] && max=$v
done
echo "$max"

Upvotes: 0

jaypal singh
jaypal singh

Reputation: 77145

This might work for you -

#!/bin/bash

max="$1"
for var in "$@"
do
    if [ "$var" -gt "$max" ] # Using the test condition
    then
        max="$var"
    fi
done
echo "$max"

Upvotes: 3

Related Questions