Search code examples
pathapplescriptfinder

How to use a variable in a POSIX Path with AppleScript?


I've been trying for a little while to swap out one of the parts in a POSIX Path with a variable but I've had no success. This is the script I'm trying to develop:

tell application "Finder"
    duplicate POSIX file "/Users/**Variable**/Documents/img.jpg" to POSIX file "/Users/**Variable**/Desktop/" with replacing
end tell

The parts in the path are the places where I want the variable to be present. How can I do this?


Solution

  • You break the string with ampersands & and the variable.

    Also, it's good practice to convert posix paths to Mac standard colon: paths prior to scripting Finder. Finder's duplicate function has been buggy since 10.9 in these ways. I have broken out some of the coercions so you can see what's going on.

    -- define file and user names
    set fileName to "img.jpg"
    set user1 to "Mitc"
    set user2 to "Mitc"
    
    -- create posix path strings
    set path1 to "/Users/" & user1 & "/Documents/" & fileName
    set path2 to "/Users/" & user2 & "/Desktop/"
    
    -- convert posix paths into colon paths
    set ref1 to (POSIX file path1) as string
    set ref2 to (POSIX file path2) as string
    
    -- display dialog ref1 & return & ref2 -- to test
    tell application "Finder" to duplicate alias ref1 to alias ref2 with replacing