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?

3
  • 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. Commented May 14, 2015 at 11:59
  • @Tom: Using separate variables enables a solution without a loop, calling set. Commented May 14, 2015 at 12:51
  • I guess I can use elements Tom. as I said I am a noob so I dont see the light yet ;) Commented May 18, 2015 at 8:19

4 Answers 4

3

You can use variable indirection for this:

for var in Q{1..50}; do
    [[ ${!var} -gt $max ]] && max=$var
done
echo \$$max
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Josh. Works like a charm and the least amount of code. Nice work and thanks again.
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

Comments

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"

1 Comment

Thanks Chepner, I appreciate all the help.
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

4 Comments

There's no need to use eval in bash.
How could I improve this?
See my or Josh Jolly's answer. You are using eval just to perform indirect parameter expansion.
I forgot to say thank you here. Help is always appreciated you all. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.