How would one evaluate priority of items in an array such that you only process the highest priority item that exists? Let me try to explain, if I had an array
set -A array low medium none high
this array is created running a command in which the array could contain any or all of the listed elements. What I want to do is evaluate on whatever the highest priority element it finds and stop looping through the array without exiting the script. In other words if low and high exist, only evaluate on high and do not keep looping through the array. If medium and low exist, only evaluate on medium and stop looping.
The only way I've found to do this so far is a horrible kludge of multiple loops entered in the order I am looking for the element. If the element is found, then I exit before it can get to the next loop but I need to not have an exit or return if that makes sense.
Here's a sample:
#!/bin/sh
set -A array low medium none high
high() {
printf "High\n"
}
medium() {
printf "Medium\n"
}
low() {
printf "Low\n"
}
none() {
printf "None\n"
}
for i in ${array[*]}; do if [ ${i} = "high" ]; then high; exit 0; fi done
for i in ${array[*]}; do if [ ${i} = "medium" ]; then medium; exit 0; fi done
for i in ${array[*]}; do if [ ${i} = "low" ]; then low; exit 0; fi done
for i in ${array[*]}; do if [ ${i} = "none" ]; then none; exit 0; fi done
With the above code, if you change the array and take out any of the elements it is almost forced to evaluate based on the hierarchy I evaluate on. If high, low, medium, none exist it'll print high and exit. If you take out high and medium it'll print low and exit.
I have another script reading this so if I exit, it exits the entire chain including the parent that loads this so I'm trying to figure out how I can stop evaluating any elements from the array once I've found the highest priority for lack of a better description.
If i take out the exists it just hits each loop and gives output for each loop. I've tried unsuccessfully with elif and else but it always evaluates every element.
Any ideas? Is it even possible to have it stop without exiting the script?
break
instead ofexit
. – mosvy Apr 18 '19 at 18:27ksh
on your system in the#!
-line./bin/sh
will generally not support arrays. – Kusalananda♦ Apr 18 '19 at 18:29/bin/sh
is Korn shell on your system, it would be Korn shell running in POSIX mode, which would quite likely be different fromksh
. – Kusalananda♦ Apr 18 '19 at 19:04