3

I have a script than closes open windows, but it only works when I have enabled the Finder "show all filename extensions" preference. Is there a robust way to accomplish this regardless of the state of the filename extension preference? I suppose I could try to close the file both with and without the extension, but that's an ugly solution

cd somedir
for file in * ; do
  echo file name is $file

osascript<<EOF
  tell application "Preview"
  close (every window whose name is "$file")
  end tell
EOF
  sleep 1
done

1 Answer 1

3

As your shell variable $file will always have a file extension in tact, you need to use the path property for Preview's document, which contains the full file path of the open file, including file extension:

cd somedir
for file in * ; do
  echo file name is $file

osascript<<EOF
  tell application "Preview"
    close (every document whose path ends with "$file")
  end tell
EOF
  sleep 1
done

This is slow, however, even without the sleep delay. Another way you could do it is to enumerate the files in AppleScript instead:

osascript<<EOF
  use sys : application "System Events"
  use Preview : application "Preview"

  script
    property list : displayed name of every file ¬
                    in sys's folder "$somedir"
  end script

  repeat with f in result's list
    tell Preview's document named f to if exists ¬
    then close
  end repeat
EOF

This is almost instantaneous, and the displayed name property specifically uses the name as it's displayed in Finder, with or without its extension. Therefore, it matches the name property of the Preview document.

You must log in to answer this question.

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