I’m working on a script that runs a shell script “with administrative privileges” so that the user is prompted to enter an administrative password in order to copy a file.
OS X displays the usual prompt that says “Application Name wants to make changes. Type your password to allow this.” If I click Cancel, the script itself doesn’t stop, but continues (and various things fail because a command couldn’t be completed when the user failed to enter a password).
I’ve tried putting the shell script in a try block and adding a line “if button returned of result” but none of these have any effect.
How can I stop the script if the user clicks Cancel at the password prompt?
An exception with the error code -60006 signifying that the user canceled will be thrown, when you run your script from with in a try error block. The funny thing is that the error number with the error code -60006, is converted into 128 before it is displayed, if you choose to display it, so, you are better off seeing the result from the script below in the results pane of AppleScript Editor.
try
do shell script ":" with administrator privileges
on error e number n
display dialog e
error number -128 #quits the script here
log "still running"
end try
How you want to leverage upon the try block is entirely up to you, you can quit directly in the try block, like I did above, or you can set a variable to true false, and test on this further down. (You initialize it above the try block of course).