0

From within a shell script (or, similarly, within a terminal) I want to reveal multiple files in Finder with all named files already selected.

Surprisingly, using open -R with multiple arguments fails to achieve this when files share a folder. For example, if I have two files, /tmp/foo/file1 and /tmp/foo/file2, then open -R /tmp/foo/file1 /tmp/foo/file2 causes a Finder window to open showing /tmp/foo but with only file2 selected, rather than both selected.

Is revealing multiple files within a single folder, with multiple files preselected, programmatically achievable?

2 Answers 2

0

Derived from an answer by @wch1zpink (since deleted), my first solution was as follows.

in reveal_files.scpt:

on run argv
  set fileAliases to {}

  repeat with filePath in argv
    copy (POSIX file filePath as alias) to the end of fileAliases
  end repeat

  tell application "Finder" to reveal fileAliases
end run

and then osascript reveal_files.scpt /tmp/foo/file1 /tmp/foo/file2 produces the desired outcome.

My second solution is in Swift via AppKit:

#!/usr/bin/swift

import AppKit

let args = CommandLine.arguments.dropFirst()
NSWorkspace.shared.activateFileViewerSelecting(args.map {
    URL(fileURLWithPath: $0)
})

and for lists of files, xargs(1) may be used e.g.

find ~/Downloads -type f -name '*.pdf' -print0 | xargs -0 reveal_files
1
0

The following Applescript will also work to reveal multiple files copied and pasted into a focused location in Finder. You can easily modify it to pass a list of filenames to theFiles instead of setting it to the clipboard, and a specific path to thePath instead of having it be set to (insertion location as alias) (i.e. the frontmost window/focused location in Finder).

tell application "Finder"
    set thePath to POSIX path of (insertion location as alias)
    set theFiles to paragraphs of (the clipboard)
    set theOutput to {}
    set theFile to {}
    
    repeat with i from 1 to count of theFiles
        set theFile to POSIX file (thePath & item i of theFiles) as text
        set end of theOutput to theFile as text
    end repeat
    
    reveal theOutput
    activate
    
end tell
--return theOutput

I wrote this and use it with a Keyboard Maestro macro when pasting items in Finder because I got tired of losing stuff in folders with a large quantity of files immediately after pasting something into them, needing to mess around with sorting, etc.

You must log in to answer this question.

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