AppleScript Bash – How to Get Error Status Back to Bash from osascript

applescriptbash

Inside a bash script, I'm closing the front window of whatever application is foreground. I'd like to know if the command failed (when the foreground application doesn't have a front window. I tried this, but even though the warning beep is heard indicating the cmd-W failed, the script always prints "Command Succeeded". What's the easy way to detect that there's no front window?

 osascript -e 'tell application "System Events" to keystroke "w" 
    using {command down}'
 if [ $? -eq 0 ]  ; then
     printf "Command succeeded\n"
 else
     printf "command failed\n"
 fi

Best Answer

Here is a bit of a different approach that does not use System Events. The following AppleScript code will get the name of the front most application, then that application will check to see if it has any open windows. If that application does have an open window, it will be closed. Also, for example, if the front application has an unsaved document as window 1, and you want to be prompted to save that document, just remove the "without saving" part of the command.

This works for me using the latest version of macOS Mojave.

delay 5 -- GIVES TIME TO TEMPORARILY SET FOCUS ON ANY OPEN APP.. FOR TESTING PURPOSES
tell application "Finder" to set appName to name of (path to frontmost application)
tell application appName to if windows is not {} then close window 1 without saving