Opening Finder from terminal with file selected

2020-06-09 11:29发布

问题:

I want to open Finder from the terminal with a specific file selected. I know that by using open . I can open the current directory in Finder, but I also want to select some file in the Finder window.

The basic thing I want to do is run a script that randomly selects a file among many in a folder and for that I need to open a new Finder window with the file selected.

回答1:

The . in your open . command just means path at current location (which would be a folder) so open decides that the correct application to use is Finder. If you were to do open myTextFile.txt which is at your current location in the terminal open will decide to use a text editor instead. You can however specify the application to open the file with by using the -a flag so your command would look like this: open -a Finder myTextFile.txt.

What Faisal suggested will also work, the -R flag is an equivalent to using ⌘↩ (Command Return) in Spotlight.

this and some other nice shell tricks with the open command are described in this post: Shell tricks: the OS X open command



回答2:

You can do it like that

osascript -e "tell application \"Finder\"" -e activate -e "reveal POSIX file \"<your file path>\"" -e end tell