首页 > 解决方案 > How to iterate through an array to populate buttons for AppleScript dialog?

问题描述

I am having issues trying to figure out how I can iterate through an array that I am using to populate labels for buttons of an AppleScript dialog box.

I currently have an array of 13 objects, which are departments for our jamf instance. An AppleScript dialog box has a max of 3 buttons you can assign. So I am trying to iterate through my array to show 2 options at a time, and the third button being "Next" to get to the next 2 options and so forth.

I also want to cover the situation for if the user has to go all the way to the last option, that it adjusts the buttons accordingly such as leaving the last dialog to have either 1 or 2 buttons if that is how many options are left.

I have set the array with the 13 items, then tried a while loop, with a nested if statement to check to see if there are 1 or 2 remaining options and to remove the extra buttons.

departments=("Accounting" "Compliance" "Data Science" "DevOps" "Engineering" "Executive Team" "Human Resources" "Marketing" "Member Experience" "Member Experience Managers" "Product" "QA" "Risk" "Not Listed")
departmentsCount=${#departments[@]}

i=0
dpt=""
while [ "$dpt" != "Not Listed" ]
do
  if [[ $((departmentsCount - $i)) -eq 0 ]]; then
    a=$i
    dpt=$(osascript -e 'Tell application "System Events" to display dialog "Please select your Department:" buttons {"'"${departments[$a]}"'"} default button 1' 2>/dev/null | sed 's/button returned://')
    i=$i+2
  elif [[ $((departmentsCount - $i)) -eq 1 ]]; then
    a=$i
    b=$(i+1)
    dpt=$(osascript -e 'Tell application "System Events" to display dialog "Please select your Department:" buttons {"'"${departments[$a]}"'", "'"${departments[$b]}"'"} default button 2' 2>/dev/null | sed 's/button returned://')
    echo "$dpt"
    i=$i+2
  else
    a=$i
    b=$i+1
    dpt=$(osascript -e 'Tell application "System Events" to display dialog "Please select your Department:" buttons {"'"${departments[$a]}"'", "'"${departments[$b]}"'", "Next"} default button 3' 2>/dev/null | sed 's/button returned://')
    i=$i+2
  fi
done

Right now I am getting an endless loop as $dpt never gets set to Other. I haven't figured out how I can get the loop to quit if something other than Next is selected. Maybe I need to change the type of loop I am using or how I am using my variables.

标签: bashshellapplescript

解决方案


I think you're using the wrong approach to this. Try a choose from list dialog instead:

osascript -e 'tell application "System Events" to (choose from list {"Accounting", "Compliance", "Data Science", "DevOps", "Engineering", "Executive Team", "Human Resources", "Marketing", "Member Experience", "Member Experience Managers", "Product", "QA", "Risk", "Not Listed"} with prompt "Please select your Department:")'

That will give your users one dialog where they can choose from all 13 departments at once. Much more user-friendly, and avoids the loop headache.


推荐阅读