Bypass “Can't get window” error in AppleScript

1.6k views Asked by At

I'm trying to make a bash script to close certain finder windows (I'm on MacOSX). Unfortunately, the script terminates as soon as the first window is found to not be open. (ex: No window titled "Communication" open, yet window "Editors" is open; No window is closed). If I open a window titled Communication, it does close, but nothing after the first command fails. I've tried exit and on error, and taking out "set -e", but nothing seems to be working. Here is my script:

#!/bin/bash
set -e
osascript <<EOF
tell application "Finder"
  close window "Communication"
  close window "Editors"
  close window "Gaming"
  close window "Music"
  close window "Technical"
  close window "Text Editors"
  close window "Utilites"
  close window "Camera"
  close window "External"
  close window "TAB Actual"
end tell

It gives me

error: 24:57: execution error: Finder got an error: Can't get window <"first window found to not be open">. (-1728) (1)

I don't know if this means anything, but the code is being run through Automator.

Thanks to anyone that can help me, and yes, I am very new to bash.

2

There are 2 answers

1
sherb On BEST ANSWER

You can use the ignoring application responses statement, for example:

#!/bin/bash
set -e
osascript <<EOF
tell application "Finder"
  ignoring application responses
    close window "Communication"
    close window "Editors"
    # More windows here...
  end ignoring
end tell

More details about control statements in the Applescript Language Guide: https://developer.apple.com/library/mac/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_control_statements.html

1
adayzdone On

This is what try statements are for:

set windowNames to {"Communication", "Editors", "Gaming"}

tell application "Finder"
    repeat with wName in windowNames
        try
            close window wName
        end try
    end repeat
end tell