1

I have 50 variables that changes value all the time. Their values are integer e.g. 1-9999, but I don't know what the values are until the script runs.

I need to display the name of the variable with the highest value. The actual value is of no importance to me.

The variables are called Q1 - Q50.

Example:

Q34=22
Q1=23
Q45=3
Q15=99

Output must just say Q15

Could you please help me in the right direction?

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
awenis
  • 11
  • 1
  • 1
    Is there any reason you're using separate variables with numeric suffixes, rather than a real array? If you used a real array with elements `${Q[0]}`, `${Q[1]}` etc., this would be much easier. – Tom Fenech May 14 '15 at 11:59
  • @Tom: Using separate variables enables a solution without a loop, calling `set`. – Walter A May 14 '15 at 12:51
  • I guess I can use elements Tom. as I said I am a noob so I dont see the light yet ;) – awenis May 18 '15 at 08:19

4 Answers4

3

You can use variable indirection for this:

for var in Q{1..50}; do
    [[ ${!var} -gt $max ]] && max=$var
done
echo \$$max
Community
  • 1
  • 1
Josh Jolly
  • 11,258
  • 2
  • 39
  • 55
1

Ask for all vars and grep yours:

set | egrep "^Q[0-9]=|^Q[1-4][0-9]=|^Q50=" | sort -nt= -k2 | tail -1 | cut -d= -f1
Walter A
  • 19,067
  • 2
  • 23
  • 43
0

this works for me, for example Q1-Q5

Q1=22
Q2=23
Q3=3
Q4=99
Q5=16

for i in $(seq 1 5); do
    name=Q$i
    value=${!name}
    echo "$name $value"
done  | sort -k2n | tail -1 | awk '{print $1}'

you get

Q4

Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62
0

Run through each of the 50 variables using indirect variable expansion, then save the name whose value is the greatest.

for ((i=1; i<= 50; i++)); do
    name=Q$i
    value=${!name}
    if ((value > biggest_value)); then
        biggest_value=$value
        biggest_name=name
    fi
done

printf "%s has the largest value\n" "$biggest_name"
chepner
  • 497,756
  • 71
  • 530
  • 681