PDA

View Full Version : AppleScript help: file exists in user directory?




Oats
Aug 12, 2007, 09:32 PM
i am trying to do some a simple applescript, but i could use some help. what i want to do is:

open the folder: ~/Documents/
check if file exists in that folder named "index.html"
if it exists, then delete the file.
if it does not exist, do something else.
then open the parent folder (looking for a generic command similar to "cd ..")

i have tried to figure this out with the "record script" option, but it always uses my current user documents folder, and i would like it to be more generic. thanks if anyone can help!



kainjow
Aug 12, 2007, 10:54 PM
Here's something to get you started:

set docsFolder to (path to documents folder as Unicode text)
set aFile to docsFolder & "index.html"
tell application "Finder"
if exists file aFile then
delete file aFile
else
-- do something else
end if

open folder docsFolder
end tell

Eraserhead
Aug 13, 2007, 05:28 AM
For what its worth, you can use do shell script("insert shell script here") in Applescript to run shell scripts.

Oats
Aug 13, 2007, 07:36 AM
thanks for the help!
i tried this, but it doesn't work:

set docsFolder to ("~/Documents")

i guess the "~" is a shell shortcut which applescript doesn't recognize? also the next thing i want to do it the equivalent of "~/Documents/../" . this might suggest i use the shell command... only problem is, with the shell command, how do i do something only if a file exists?

Eraserhead
Aug 13, 2007, 07:55 AM
You need to switch between OS X and Unix paths to do it, see this (http://lists.apple.com/archives/Applescript-users/2004/Mar/msg01073.html) for how.

kainjow
Aug 13, 2007, 08:45 AM
thanks for the help!
i tried this, but it doesn't work:

set docsFolder to ("~/Documents")

i guess the "~" is a shell shortcut which applescript doesn't recognize? also the next thing i want to do it the equivalent of "~/Documents/../" . this might suggest i use the shell command... only problem is, with the shell command, how do i do something only if a file exists?

You are thinking in terms of shell scripting, not AppleScript. AppleScript can do some of this stuff, but it'd be easier to do it in a shell script (using Bash):

#!/bin/bash
DOCSDIR="${HOME}/Documents"
FILE="${DOCSDIR}/index.html"
if [ -e $FILE ]; then
rm $FILE
#else
# do something else
fi
open $DOCSDIR

Save it as myfile.command, then in Terminal run "chmod 755 <path-to-myfile.command>" and then you can double-click and it will open in Terminal and run.

this (http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html) page has lots more info on bash scripting.

Oats
Aug 13, 2007, 10:13 PM
thanks so much! you guys are the best.