Note: This code only works with AppleScript studio apps (Xcode).
This scriptlet can find out the directory that the app is running from. The point of this scriptlet is to make it easier to write code that works no matter what directory the application is in, since the current running directory is saved to a variable that you can use in your code. This is useful when your app uses support files in the same directory it runs from, rather than just the application bundle. I’m relatively new to AppleScript and there might be an easier way to do this, but here’s my code:
--GetAppDir Scriptlet by wizboyx86 (pcwiz)
on getAppDir(appname)
return (do shell script "echo " & "'" & (path of main bundle) & "'" & " " & "| sed 's/" & appname & "//'") as text
end getAppDir
So how would you use this?
Say you wanted to get the full path for “/files/textfile.txt”. You would do (replace “myapp.app” with the actual name of your application, don’t remove the quotes!):
set txtfile to (getAppDir("myapp.app") & "files/textfile.txt")
This would return like “/path/to/app-directory/files/textfile.txt”. Try it for yourself and see what it returns. It should work regardless of what directory the app is in.
There is an applescript way without using the command line:
tell application "Finder" to set myFolder to (container of (path to me)) as string
Unfortunately neither of these actually returns something useable. While they do return the path, the problem I’m having is that’s only good for displaying at plain text output, you can’t pass that path back to a command. Why? Spaces. Yes the bane of command line, the space. If there is a space in my app name, or any directory getting to it, I’m hosed. I need a way to find out where the application is so that I can then pass a do shell script to a command line utility that I am putting in the application resources. I have tried this 4 different ways, and in every case I slam into the first space in a directory name and get an error. Any ideas?
This is easily handled. The ‘do shell script’ command’ has a tool for that called ‘quoted form of’ which puts quotation marks around the path and thus spaces do not impact the shell command. Also, with paths you have to worry about if the path is in mac form (with a colon : between the path variables). If it is you use the command ‘posix path of’ to change the mac form to the posix form (with a slash / between the path variables) so the shell can handle it. For example…
– this is a path in text format and may or may not contain spaces, also it is in mac form
tell application “Finder” to set myFolder to (container of (path to me)) as string
do shell script "echo " & quoted form of posix path of myFolder
son of… I spent 2 hours looking for this answer today, tried both quoted form and posix path of, just not together! sigh thank you regulus, you win the prize!