MacOS – Set the Working Folder of `.app` Created by Apple Script

applescriptbashcommand linemacosterminal

I have a simple Shell File .sh which copies files form the PWD to a destination folder.
This is basically Hand Made installer of a program.
I want to create an APP from it.

The idea is to have the following structure of the files at the user:

- MyApp
    - SourceFiles/
    - MyInstaller.app

Something like:

#!/bin/sh

# Copying

cp -r './SourceFiles/.' '/DestFolder/SourceFiles/'

exit 0

I created an Apple Script (MyInstaller.scpt) file which looks:

tell me to activate

display dialog "Run My Installer?" buttons {"Run", "Cancel"} default button 1

if the button returned of the result is "Run" then
    do shell script "cp -r './SourceFiles/.' '/DestFolder/SourceFiles/' & exit 0;" with administrator privileges

    display dialog "Finished Successfully!" buttons {"OK"} default button 1

end if

I compile it with osacompile -o MyInstaller.app MyInstaller.scpt.

Then I try to run MyInstaller.app it doesn't work.
Though if I run the sh Shell Script form the same location it works.

I had a feeling it is related to the PWD of the APP when it runs.
So I did the following trick, I compiled an .APP from the following Apple Script:

do shell script "pwd > ~/Temp.txt & exit 0;"

Then I saw at Temp.txt that the PWD is / (Namely the Root).
Indeed if I copy SourceFiles/ to the root and run the APP it copes the files correctly.

Is there a way to make the APP of the AppleScript to run relative to the location of the compiled APP?

Best Answer

One way to handle this is to set a variable, e.g. myPath, and build out from there.

set myPath to POSIX path of (path to me as text)

The myPath variable will be returned in the form of:

/path/to/AppName.app/

You can then concatenate myPath and addition path segments and filename as needed.

Note that when using this in a do shell script command, use quoted form of to allow for spaces in the path filename.


Have a look at the AppleScript Language Guide and more specifically: path to (application)

path to (application)

Returns the location of the specified application.

...

  me

    The script itself. For script applications, this is the same as current application, but for script documents, it is the location of the document.