Get current_path if using AppleScript as osascript expression

I have a following AppleScript:

tell application "Finder"
    set current_path to container of (path to me) as string
    duplicate file (current_path & "foo.txt")
end tell

It works, but I need to pass it an osascript expression. That is, the whole workflow looks like:

  1. Open the Terminal app

  2. Execute

    cd ~/test
    

    (the folder in which the foo.txt file and the bar folder are located).

  3. Execute

    osascript -l AppleScript -e 'tell application "Finder"' -e 'set current_path to container of (path to me) as string' -e 'duplicate file (current_path & "foo.txt") --to folder (current_path & "bar")' -e 'end tell'
    

The problem is that current_path is now treated to be Macintosh HD:usr:bin and not Macintosh HD:Users:user:john:test. How to fix this?

bash - Why can’t I change directories using “cd” in a script? - Stack Overflow

Shell scripts are run inside a subshell, and each subshell has its own concept of what the current directory is. The cd succeeds, but as soon as the subshell exits, you’re back in the interactive shell and nothing ever changed there.

1 Like

Do you have any opportunity to pass in a shell/path variable to the osascript one-liner?

E.g., here’s your script if you were duplicate current_directory/foo.txt to current_directory/bar/foo.txt. pwd prints the current directory and then it’s interpolated.

filePath=$(pwd) && osascript 
-e "tell application \"Finder\"" 
-e "set targetFile to (POSIX file \"$filePath/foo.txt\" as alias)" 
-e "set destinationFolder to POSIX file \"$filePath/bar\" as alias" 
-e "duplicate targetFile to destinationFolder" 
-e "end tell"
1 Like