MacOS – AppleScript and Finder – How to detect an “empty” selection when copying paths to the clipboard (Expanded Question)

applescriptcopy/pastefinderfolder-actionmacos

I'm trying to build a Service that does the following:

  • If some folder/files are selected in Finder, copy (all) the paths to the clipboard
  • If nothing is selected, copy the "Path" of the window.

Digging around and getting inspiration from posts such as Copying the current directory's path to the clipboard and MacYourself's Copy file or folder path to the clipboard in Mac OS X Lion I've got to the point where I can get the paths of the selection, but I seem to be stuck when trying to get the path of the current window if selection empty.

UPDATE 13-Dec-2013. I've got some useful feedback (see https://apple.stackexchange.com/a/113612/7488; thanks @Flavin) so I have updated the code to the one below:

    on run {input, parameters}

        set l to {}
        tell application "Finder"
            set sel to (get selection)
            if not sel = {} then -- there are some file/folders selected

                repeat with f in (get selection)
                    set end of l to POSIX path of (f as alias)
                end repeat

            else --no stuff is selected, get the current location path

                set end of l to POSIX path of (insertion location as alias)

            end if
        end tell
        set text item delimiters to linefeed
        set the clipboard to (l as text)

    end run

The logic seems solid, and it works as long as I have "something" selected in Finder.

I suspect that the Service might not be "Active" when there is nothing selected, (that is, when the desired result would be to copy the current path to the clipboard).

In this situation, the Finder window appears thusly:

Finder With nothing selected

But trying to active the Service shows an "empty" service list:

Finder No services apply

When I have something selected, the Services list is populated:

Services Available when some File is selected

The "Copy File Path" that I've defined is associated with "Files and Folders" in the Services Preferences — what might be the issue?

Best Answer

I think = is what you're looking for.

set sel to (get selection)
if not sel = {} then
    --stuff is selected
else
    --no stuff is selected
end if

Or remove the not and flip the cases

set sel to (get selection)
if sel = {} then
    --no stuff is selected
else
    --stuff is selected
end if