trying to check for file and then delete it

Is there something wrong with this?
I want to check to see if a file exists . . . if it does then delete it otherwise create it.


	if file "$HOME:Desktop:DetoX.txt" exists then
		do shell script "rm $HOME/Desktop/DetoX.txt"
	else
		do shell script ">$HOME/Desktop/DetoX.txt"
	end if


Yes, there is a problem here: you’re trying to use a shell variable inside a regular AppleScript command. AppleScript is looking for a file in a disk named $HOME, which I’m guessing does not exist.

Also, the ‘exists’ command belongs to the Finder, so you’d need to put that in a tell block. How about this? I’ve got a handler that tests if a file exists at a given AppleScript path:


if testPathExists((path to desktop as string) & "DetoX.txt") then
   do shell script "rm $HOME/Desktop/DetoX.txt"
else
   do shell script ">$HOME/Desktop/DetoX.txt"
end if

on testPathExists(inputPath)
	-- version 1.4
	-- from Richard Morton, on applescript-users@lists.apple.com
	-- public domain, of course. :-)
	-- gets somewhat slower as nested-depth level goes over 10 nested folders
	if inputPath is not equal to "" then try
		get alias inputPath as string
		return true
	end try
	return false
end testPathExists

There’s another problem here. Your “do shell script” command is malformed. “>” takes the output of the command on the left side and writes it to the file on the right side. For example:

do shell script "ls / > ~Desktop/ls.txt"

This would take the output of ‘ls’, and put it in the file ‘ls.txt’ on the Desktop. If the file ls.txt already existed, it would attempt to overwrite it.

If instead of creating a file with contents, you’d like to create a new blank file, the touch command may be more to your liking.

bog

Good catch. I missed that part. :slight_smile: He did say that he wanted to create the file, so touch is what he wants.

Using greater than redirection is a standard way of creating a file in UNIX, which doesn’t require any external commands. It should work just fine. Unless you were trying to make a different point.

Interesting. It works in do shell script (straight ‘sh’, but it doesn’t work in a Terminal window (usually ‘tcsh’). You get the following:

Invalid null command.

Seems to me that this does not work in some shells, whereas touch works everywhere, right? I’d stick to touch.