Reputation: 11
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?
Upvotes: 1
Views: 506
Reputation: 20002
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
Upvotes: 1
Reputation: 8164
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
Upvotes: 0
Reputation: 531215
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"
Upvotes: 0
Reputation: 11786
You can use variable indirection for this:
for var in Q{1..50}; do
[[ ${!var} -gt $max ]] && max=$var
done
echo \$$max
Upvotes: 3