exists with string literal vs string variable

This is driving me absolutely nuts. If I run the following code, I get the expected result (“exists”):

tell application "Finder"
	if exists POSIX file "/Users" then
		"exists"
	else
		"not exists"
	end if
end tell

However, if I run this minor variation of that code, I get exactly the opposite result (“not exists”), despite the fact that the only difference is that the string is in a variable!!!

tell application "Finder"
	set curPath to "/Users"
	if exists POSIX file curPath then
		"exists"
	else
		"not exists"
	end if
end tell

What is going on here?

Hi.

In the first script, the POSIX file specification’s worked out by the compiler and compiled into the script.

In the second, the string’s put into a variable when the script runs and the Finder’s told to work out the POSIX file from that. But the Finder doesn’t know how to do it, even though it understands the result when it’s done. Two possible workarounds are to work out the POSIX file before the Finder statement or to put ‘my’ in front of the expression so that the script, rather than the Finder, does the conversion:

tell application "Finder"
	set curPath to "/Users"
	if exists my POSIX file curPath then
		"exists"
	else
		"not exists"
	end if
end tell

Further to Nigel’s answer, you can also use “curPath as POSIX file”.

However, it’s worth keeping in mind that POSIX file is defined in Standard Additions, not AppleScript itself – it’s actually a sort of pseudo-class. So I think the better course is Nigel’s first solution, to remove it from the Finder tell block, like this:

set curPath to "/Users"
set theFile to POSIX file curPath
tell application "Finder"
	if exists theFile then
		"exists"
	else
		"not exists"
	end if
end tell

The problem with using my is that it too will fail in some circumstances (for example, if there’s a use frameworks statement).

Or use system events who supports posix paths without explicitly using the posix file and pseudo classes. It’s quite an understatement that the old Carbon style paths are outdated and the Finder should be supporting directly POSIX path strings.

tell application "System Events"
	if exists disk item "/Users" then
		"exists"
	else
		"not exists"
	end if
end tell

Thanks for all the explanations. I’ve got my code working now.

There are some things I really like about AppleScript, but this kind of inconsistency is not one of them. :confused: