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?
Many thanks for any help with this.
The shell script won’t run if the user cancels. I don’t get it.
do shell script "echo 'hello world'" with administrator privileges
display dialog "Continuing ..."
If the user cancels, the script errors. Did you mean that you don’t want it to error?
Here’s a better example:
do shell script "osascript -e 'display dialog \"Contiuing ...\"'" with administrator privileges
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.
do shell script ":" with administrator privileges
on error e number n
display dialog e
error number -128 #quits the script here
log "still running"
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).
Thank you, McUsrII - I should have thought of adding “error number -128” in case of an error, but I didn’t!
You’ve solved the problem completely.
Oh I see now, because the user canceled error allows it to exit gracefully.