AppleScript: Current Directory

I wanted to create an AppleScript to launch a shell script. The problem I ran into is whenever I do a shell script the working directory is my home directory. I need to find out a way to change the directory to the current directory.

With the help of this book and some hints I googled, I finally found the correct combination. Here is the code.

tell application "Finder" to get folder of (path to me) as Unicode text

set workingDir to POSIX path of result

The code stores current directory in variable workingDir in POSIX format. You can then use it in your shell script.

  • Jafraldo

    Hiya, thanks for this.

    It would be a help to newbs like me if you expanded a bit to show how to use the applescript variable inside the ‘do shell script’ command.

    do shell script “ls $workingDir” doesn’t work.. yeah I know newb and I should just experiment more to figure it out, but it would have been convenient if you gave it in the example!

  • Jafraldo

    set hostname to “www.apple.com”
    do shell script “ping -c1 ” & hostname & ” | /dev/null”

  • JG

    Here is an example, this will cd to the the folder containing the appleScript and write it’s path to a file named out.txt:

    tell application “Finder” to get folder of (path to me) as Unicode text
    set workingDir to POSIX path of result
    do shell script “cd ” & workingDir & “;” & “echo `pwd` > out.txt”