How can I Convert ~/ File Path to usable form for AppleScript?

Apologies if this is obvious but I haven’t found the answer after a bit of Googling.

I know that an AppleScript variable can be set to a file path if the path is quoted like:

“Macintosh HD:Users:myname:test folder”

But is there a way I can I pass the path written as below to AppleScript?

~/test folder

This script returns both POSIX and HFS paths–it is based on a suggestion by Shane.

set folderLocation to "~/Test Folder"
if folderLocation begins with "~" then set posixPath to (POSIX path of (path to home folder)) & text 3 thru -1 of folderLocation --> "/Users/Robert/Test Folder"
if folderLocation begins with "~" then set hfsPath to (POSIX file ((POSIX path of (path to home folder)) & text 3 thru -1 of folderLocation)) as text --> "Macintosh HD:Users:Robert:Test Folder:"

Just for the sake of completeness:

use framework "Foundation"
use scripting additions

set folderLocation to "~/Test Folder"
set folderLocation to current application's NSString's stringWithString:folderLocation
set posixPath to folderLocation's stringByExpandingTildeInPath() as text --> "/Users/Robert/Test Folder"
set hfsPath to (current application's |NSURL|'s fileURLWithPath:posixPath) as text --> "Macintosh HD:Users:Robert:Test Folder:"
1 Like

Thanks @peavine - that works like a charm and is exactly what I was looking for!

I have an AppleScript library that handles this for you:

There is an undocumented function called makeFileReference Which converts anything (POSIX path string, HFS string, alias, etc.) into a file reference you can use.

1 Like

Thank you @alldritt, I hadn’t come across that before. I will check it out now.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.