Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

Select files in Finder from Terminal UNIX
I wanted to be able, from the Terminal, to select files in the Finder. That is, to use a command like this...
showinfinder /Developer/Tools/GetFileInfo /Developer/Tools/SetFile
...and have Terminal open the Finder, with the specified file(s) selected.

The command open wasn't useful in this case, because I wanted the files to be selected. And sometimes I have the complete path file in the clipboard, and it annoys me to have to strip the name off, and then in the Finder, look for this file.

My solution is an AppleScript called via a function in the shell. This way, you can also use completions from the shell to specify one or several files. If you call it normally, you will have to give the arguments with an absolute path. But, if the first argument is Current_path:path, then the script will look in the folder path to find files.

Next I added this function in my alias file (I use the zsh shell). It takes care of providing the current directory:
function showinfinder() {
    thepath=`pwd`;
    args="";
    while [ $# -ne 0 ]; do
        args=`echo "$args $1"`;
        shift;
    done
    echo "/path/to/the/script/FinderSelect.scpt" \
    "Current_path:$thepath" "$args" | xargs osascript;
}
Make sure you replace /path/to/the/script/FinderSelect.scpt with the actual (full) path to your saved AppleScript. And here's an example of how it's used:
showfinder -a toto /tmp/toto2
This will add /tmp/toto2 and toto from the current directory to the current selection, and show them in the Finder. Like the script from this hint, I have the same bug and have no idea how to fix it. Any ideas?
    •    
  • Currently 3.00 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (2 votes cast)
 
[15,796 views]  

Select files in Finder from Terminal | 13 comments | Create New Account
Click here to return to the 'Select files in Finder from Terminal' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Select files in Finder from Terminal
Authored by: FangVT on May 24, '06 11:22:33AM

Wow, that's a lot of extraneous shell code.

The whole loop to build the arguments variable is not needed, just use $* or $@.

So the function then becomes:

function showinfinder() {
thepath=`pwd`;
echo "/path/to/the/script/FinderSelect.scpt" \
"Current_path:$thepath" "$*" | xargs osascript;
}

Now let's not waste time setting up a temporary variable to hold the current directory.

So the function now becomes:

function showinfinder() {
echo "/path/to/the/script/FinderSelect.scpt" \
"Current_path:`pwd`" "$*" | xargs osascript;
}

I'm not really familiar with xargs and I can only glean so much from a quick skim of the man page, but I think you don't need it.

So the final function might just need to be:

function showinfinder() {
osascript "/path/to/the/script/FinderSelect.scpt" \
"Current_path:`pwd`" "$*"
}



[ Reply to This | # ]
Select files in Finder from Terminal
Authored by: masjones on May 24, '06 12:00:33PM

Wouldn't it be easier to use LaunchBar or Butler or even the Finder itself to find a specific file? Especially since oyu know its name?

I do not ever use the Terminal so maybe I am missing something.

Mj



[ Reply to This | # ]
Select files in Finder from Terminal
Authored by: mistersquid on May 25, '06 06:20:25AM
I do not ever use the Terminal so maybe I am missing something.

Not to be harsh but, yeah, you definitely are missing something. In particular, there are times when one is working at the command line and wants to open selected files in the GUI without having to navigate using the GUI.



[ Reply to This | # ]
Select files in Finder from Terminal
Authored by: rwmitchell on May 24, '06 01:32:16PM

For the tcsh, I created an alias:

alias sf 'osascript ~/bin/selectfinder.scpt Current_path:`pwd` $*'

which seems to work for me. (note that my alias has the path to the script hardcode, so adjust that for your environment)


to the person wondering why you'd want to do this instead of just using the finder, there are some situations where it is easier to wildcard a selection than it is select in the finder. A case where the middle of the filename has some uniq attribute that you want to select for. To the rest of us command line unix diehards, it just feels more natural :-)



[ Reply to This | # ]
Select files in Finder from Terminal
Authored by: Lutin on May 25, '06 05:12:17AM
Thank you for the improvement.

function showinfinder() {
   osascript "/path/to/FinderSelect.scpt""Current_path:`pwd`" "$@"
}
works for me (but $* didn't).

[ Reply to This | # ]
Select files in Finder from Terminal
Authored by: magir on May 24, '06 01:23:31PM

It might be easier to implement using an Applescript droplet. The finder has the verb "reveal" which simply takes the reference as argument.

I though about using an alias for "open -a <droplet> " and writing a simple droplet which reveals the files dragging onto it. Sadly it wasn't as simply as I thought but if someone else with more Applescript experience gives it a try it might like nicer than the given solution.



[ Reply to This | # ]
Select files in Finder from Terminal
Authored by: ever on May 24, '06 05:23:06PM
Good idea. That worked fine for me…
to open these_files
	tell application "Finder" to reveal these_files
end open
…saved as an app bundle and used like
open -a /path/to/bundle /path/to/files


[ Reply to This | # ]
Select files in Finder from Terminal
Authored by: cougar718 on May 24, '06 08:56:48PM

If you're going to go to the extent of draggging and dropping files on to a droplet, why would you not select the files instead of dragging them.

I think the hint needs to select the files from the shell and simply show them to the user which the Finder does automatically via AppleScript when you choose to reveal a reference.

As of right now, ever's solution below seems to be unusable because you can only select 1 file.

I'm not sure if AppleScript can handle multiple files references from BASH. The best solution for this hint is to use BASH scripting and create a shell script which calls osascript -e and compile AppleScript code on the fly.

Good luck! If I figure anything out, I'll reply.

---
Rick alias cougar



[ Reply to This | # ]
Select files in Finder from Terminal
Authored by: ever on May 25, '06 09:43:33AM

Hehe, unusable for you, maybe. :p There is no dragging and dropping involved of course. It could use accepting multiple files tho, I didn't catch that. That appears to be a limitation of the open -a command though, as my droplet can accept and select multiple file references simultaneously as-is. Hmm. Oh well, I'll never use it anyway. :)



[ Reply to This | # ]
fix for column view bug
Authored by: mzs on May 25, '06 08:15:56PM
I liked this hint a lot, so I improved it. First of all I made it so that I can have the Finder select files with international characters in them. Also I made it so that the compiled AppleScript and the shell script are in the same file. The methods for doing this are detailed in this hint. I also figured-out a work around for the column view bug and I cleaned-up it up a bit.

First create this Makefile:


.SUFFIXES : .applescript .scpt

.PHONEY : install

TARGET = sf
PREFIX = /usr/local
BINDIR = ${PREFIX}/bin

${TARGET} :

install : ${TARGET}
	mkdir -p ${BINDIR}
	ditto -rsrc $< ${BINDIR}

.applescript.scpt : ; osacompile -o '$(subst ','\'',$*)'.scpt -- '$(subst ','\'',$<)'

% : %.scpt %.shosa
	ditto -rsrc '$(subst ','\'',$*)'.scpt '$(subst ','\'',$@)'
	chmod a+x '$(subst ','\'',$@)'
	cat -- '$(subst ','\'',$*)'.shosa > '$(subst ','\'',$@)'
Be sure that every place it looks like there are eight spaces at the beginning of a line is in fact a single tab character in the Makefile otherwise make will choke.

Here is the contents of the shell script portion, sf.shosa:


#!/bin/sh

# Add -a in the arguments to keep the current selection of the front most
# window of the Finder selected while dealing with args of the command line.

usage() {
        echo "Usage: ${0##*/} [-a] [--] filename [ filename... ]" >&2
        exit 1
}

errexit () {
        echo ${0##*/}: "$1" >&2
	usage
}

case $# in
    0)
        errexit "too few arguments"
        ;;
esac

addtocurrentselection=''
case "$1" in
    -a)
	addtocurrentselection=1
	shift
        ;;
    --)
	shift
        ;;
esac
export addtocurrentselection

case $# in
    0)
        errexit "too few arguments"
        ;;
esac

{
        case "$1" in
            /*)
                arg=$1
                ;;
            *)
                arg=$PWD/$1
                ;;
        esac

        echo -nE "$arg"
        shift

        for arg in "$@"; do
                case "$arg" in
                    /*)
                        ;;
                    *)
                        arg=$PWD/$arg
                        ;;
                esac

                echo -ne '\x00'; echo -nE "$arg"
        done
} | /usr/bin/osascript -- "$0"
Finally here is the AppleScript half of the hint, sf.applescript:

-- Read the arguments from stdin so that international
-- characters do not get munged.
set argv to do shell script "/bin/cat"

-- Break-up the arguments into a list.
set AppleScript's text item delimiters to ASCII character 0
set argv to argv's text items
set AppleScript's text item delimiters to {""}

-- See if we create a new selection or add to the current selection.
if (system attribute "addtocurrentselection") is "" then
	set sel to {}
else
	tell application "Finder" to set sel to selection as list
end if

set found to false
repeat with ritem in my argv
	set pf to POSIX file ritem
	
	try
		-- Coercing to an alias will check to see if it exists.
		-- Using item works for folders, files, aliases, etc.
		set fpf to item (pf as alias) of application "Finder"
		set found to true
		set end of my sel to fpf
	end try
end repeat

-- No reason to do anything in the Finder unless some item existed.
if found then
	tell application "Finder"
		-- In column mode, if only folders are selected, the
		-- naive approach does not work as expected. The
		-- selection will only be the last folder of the window.
		--
		-- Therefore a work-around is used. For each window
		-- which is in column view, we retarget it to its parent
		-- and set it to icon view. Then we restore the windows
		-- to column view.
		--
		-- The only problem with this approach is that if the
		-- parent of the item is itself in column view then it
		-- may now be in icon view (depending on if the Finder
		-- has any other Windows open of the parent and when
		-- which which window is closed). I use column view so
		-- rarely that this isn't really a problem.
		set cvl to {}
		repeat with ritem in my sel
			reveal ritem
			
			set fw to front window
			if (current view of fw) is column view then
				set tg to target of front window
				set target of fw to parent of tg
				set current view of fw to icon view
				
				-- tuck-away the window so we can restore
				-- it to column view later.
				set end of my cvl to contents of fw
			end if
		end repeat
		
		-- Select the the items in the Finder.
		select my sel
		
		-- Now restore the windows that were in column view.
		repeat with ritem in my cvl
			set current view of ritem to column view
		end repeat
		
		-- bring the Finder to the front.
		activate
	end tell
end if

return
Type make sf to build sf and type sudo make install to install the sf script into /usr/local/bin. Then sf works just like the script in the hint. This should work in 10.3 as well as 10.4, but I have only tested it on 10.4. I think I will be using this a lot and the original hint was a clever idea.

[ Reply to This | # ]
one more bit
Authored by: mzs on May 25, '06 08:32:36PM

You do not need to use "Current_path:" in the sf script. All arguments can be relatie or absolute. For example, this will work:

sf ~ /Library .



[ Reply to This | # ]
YA modified version
Authored by: caesurae on May 27, '06 01:13:18PM
I also liked the hint and created my own version which i believe is less complex than others' scripts (definitely less verbose).

The entire solution exists as a bash script which calls osascript for a one-liner AppleScript statement for each argument given and then activates Finder. If no directory/path is given, then it looks in the current working directory. Otherwise, paths can be relative to ~ (home) or / (root), and can include spaces as long as "quotes" are used.

I usually make aliases (tcsh) to my scripts, in this case i chose... alias rev ~/bin/revealInFinder.bash. So to use the script, I simply type something like;

rev file1 ~/folder/file2 "/folder x/folder y/file 3" etc.

I don't want to chance posting the script in this web forum environment due to some very specific quoting schemes used to allow files/paths with spaces. Instead, you can click here to download it.

I have considerably less experience in shell scripting than with AppleScript, so if any shell gurus out there have some more efficient and/or robust syntax, I'd love to see it. However, I do believe the script to be fairly reliable, and #comments are included so you can see the how and why of the methods i have chosen.

Thanks again to Lutin for the submission.

[ Reply to This | # ]

Another approach
Authored by: wgscott on May 27, '06 09:54:24PM
This is something I came up with that uses code from Gary Kerbaugh's posd function, a function that returns the path of the frontmost finder window.


function selectfile {
osascript << eof
try
tell application "Finder" to set the source_folder to (folder of the front 
window) as alias
on error -- no open folder windows
	set the source_folder to path to desktop folder as alias
end try

set thePath to (POSIX path of the source_folder as string)
set result to thePath

set PosixFile to thePath & "/" & "$@"

set CompletePath to POSIX file PosixFile

tell application "Finder"
	select CompletePath
end tell
eof
}

Typing the command

selectfile My File.txt


will select the file My File.txt in the frontmost finder window, and if no finder window is open, it will select it on the desktop. It also works for files that don't have spaces in their names. :)

[ Reply to This | # ]