MacOS – Can automation service to get the parent folder path

automationautomatormacosscriptservices

I already have a service that will create a network file:/// link to a share point over AFP but I would like to have one that does the parent folder of a file.

If I right click a file I would like to have the option to either choose to copy the file path to the file or the files parent folder.

I would prefer that the script be in Shell / bash and not in AppleScript and my dream scenario would be a way to copy both the file path and file path parent folder to the clipboard. Then when I pasted it would look like this:

File Path:
file:///Volume/parentfolder/file.pdf
Parent Folder:
file:///Volume/parentfolder

Preferably I would like to obtain four lines of text in the clipboard in one action, but the second half (parent folder) is the one I lack currently.

Best Answer

Create a new Automator Service, with the following settings:

  • Service receives selected [files or folders] in [Finder]

Add a Run Shell Script action, with the following settings:

  • Shell [/bin/bash]               Pass input [as argument]

Replacing all of the default code with the example code below:

toTheClipboard="File Path: file://$(sed 's: :%20:g' <<< "$1") Parent Folder: file://$(dirname "$1" | sed 's: :%20:g')"
pbcopy<<<"$toTheClipboard"

Save the Automator Service, then in Finder, select an item and right-click selecting the service from the Services context menu. The service is also available from the Finder > Services menu.

You can then paste from the clipboard to wherever you want it.


Note: The example code is just that and does not employ any error handling and is meant only to show one of many ways accomplish a task. The onus is always upon the User to add/use appropriate error handling as needed/wanted.