2

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.

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
  • If possible, maybe find a way to detect when the windows are open, and close the open windows individually after blank amount of time? – Miles Milosevich Nov 15 '14 at 21:24
  • Welcome to bash! Not too familiar with OSX but from a bash perspective, I recommend that you 1) Run it from iterm or something so you can see what's going on 2) add set -x to your script as well - that will print out lots of useful debug information including how far your stuff has gotten 3) That < – fquinner Nov 15 '14 at 21:29
  • This is an AppleScript, not a bash question. Bash is only running one command - `osascript` - so what it does when `osascript` errors is irrelevant. The problem is that `osascript` stops when any of the `close window` statements fails, so you need to fix that. – Mark Reed Nov 15 '14 at 21:51
  • @MarkReed oh, well I sound stupid then – Miles Milosevich Nov 16 '14 at 05:41

2 Answers2

1

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

sherb
  • 5,845
  • 5
  • 35
  • 45
1

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
adayzdone
  • 11,120
  • 2
  • 20
  • 37