0

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
  • Whether or not the frontmost app has a window showing that given osascript command will allways exit 0 because all it's doing is pressing ⌘W. You're going have to trap a different way. Maybe first check to see if the frontmost app actually has a visible window before trying to use osascript and System Events to press keys. – user3439894 Mar 5 at 2:52
1

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
1

As mentioned, the result of osascript is not the same as the result from the script. What I do is use the -so option to also print errors on stdout, then use the exit code from osascript to determine how to treat the result:

osascript -s o -e 'error number -128'

will error and also return an error message/number from the script - User canceled. (-128), while

osascript -s o -e 'tell application "System Events" to keystroke space'

exits normally and won’t generate an error.

You need to be more specific when trying to generate errors, for example try to get the front window, which will generate an error if there isn’t one.

You must log in to answer this question.

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