Search code examples
bashbuttonscriptingosascript

Buttons aren't functioning correctly with osascript


I have a dialog box that has two buttons, "OK" and "Cancel", I'd like to have the "OK" button launch a website, and the cancel button will stop the script. Right now both the "OK and "Cancel" buttons are launching the website. What am I missing here?

osascript -e 'tell app "System Events" to display dialog "Things are broke \r \rPress OK to launch Google" buttons {"Cancel", "OK"}'
if [ "button returned:OK" ]; then 
    open "http://www.google.com"
else
    exit 0
fi

Solution

  • There are a couple of options. The first is easier maybe:

    osascript -e 'tell app "System Events" to display dialog "Things are broke \r \rPress OK to launch Google" buttons {"Cancel", "OK"}' >/dev/null 2>&1
    if [ $? -eq 0 ]; then open "http://www.google.com"; else exit 0; fi
    

    Or capture and parse the output of osascript like this:

    res=$(osascript -e 'tell app "System Events" to display dialog "Things are broke \r \rPress OK to launch Google" buttons {"Cancel", "OK"}' 2>/dev/null)
    

    Then you can check like this:

    if [[ $res == *OK* ]]; then 
      echo OK
    fi