2

Here is my basic script:

#!/bin/bash

osascript  -e 'tell application id "com.apple.systemevents"'
-e 'display dialog "Do you want to continue?" & return & return &
 " Please wait..." buttons {"Cancel", "Okay"} default button
2 cancel button "Cancel"' -e 'end tell' -e 'if button returned is "Cancel" then'
-e '<blah blah kill this script>' -e 'end if'

-- other bash stuff here

I need the script to stop if the user clicks the "Cancel" button. As it is now the script waits until the user clicks either button and then proceeds to run the bash code. How can I kill the script?

This to be able to run on Mac OS 10.6 through 10.10, no third-party add-ons.

1 Answer 1

3

How about this?

  • It works on my 10.6 Macbook.
  • It is cleaner than having to escape quotes etc...
  • osascript returns a status like normal unix programs.
  • Bash script aborts on a status 1 from osascript.
  • No unnecessary messages from osascript - >dev/null 2>&1

I don't have anything else to test it on. You may need to adjust for other versions of OSX.

#!/bin/bash

osascript >/dev/null 2>&1 <<-EOF
tell application id "com.apple.systemevents"
   set myMsg to "Do you want to continue?" & return & return & " Please wait..."
   set theResp to display dialog myMsg buttons {"Cancel", "Okay"} default button 2 
end tell

# Following is not really necessary. Cancel returns 1 and OK 0 ...
if button returned of theResp is "Cancel" then
   return 1
end if
EOF

# Check status of osascript
if [ "$?" != "0" ] ; then
   echo "User aborted. Exiting..."
   exit 1
fi

#-- other bash stuff here
echo "All good, moving on...."

HTH

4
  • Thanks. I tried enclosing the osascript in EOF before and in my situation it does not work. Somehow it won't execute the bash part of the script only the applescript, that's why I used the osascript -e. The script is part of a Wineskin wrapped application. The script is executed through one of the Help menu items. Apr 7, 2015 at 20:41
  • I ended up adding ` || exit 0`, which does exactly what I need it to do, but don't understand why. Otherwise I'd answer this question myself. The person who told me about it wouldn't explain it to me. Maybe some genius around here can enlighten us. :) Apr 7, 2015 at 21:02
  • How is using EOF not working for you? Did you get an error? As to your || exit 0, it's a logical OR operator used as a short hand version for the if ... then block. If your osascript returns it 0 then the it doesn't execute the second part, if not then it has to do the second part.
    – Vic
    Apr 8, 2015 at 19:24
  • The dialog happens, but pressing either button has no effect on the remaining script. It's like the script ends. I don't know how to read the echo so I don't know what the error may be if it outputs one, where does it output to? Apr 9, 2015 at 2:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .