8

I am trying to get the name of file using AppleScript with the following code:

tell application "Finder"
    set filename to name of "/Users/mainuser/Desktop/Test/shot.png" // should return  shot.png
    display dialog filename
end tell

I am getting an error saying:

error "Can’t get name of \"/Users/mainuser/Desktop/Test/shot.png\"." number -1728 from name of "/Users/mainuser/Desktop/Test/shot.png"

What I am doing wrong?

0

1 Answer 1

12

Using the file pathname from your question, here is the AppleScript code that should work.

tell application "Finder"
    set fileName to name of (POSIX file "/Users/mainuser/Desktop/Test/shot.png" as alias)
    display dialog fileName
end tell

A more direct way of the above scenario is:

Syntax:

set fileName to name of (info for "/path/to/file")
display dialog fileName

Example (using the pathname in your question):

set fileName to name of (info for "/Users/mainuser/Desktop/Test/shot.png")
display dialog fileName

The shortest way to display the name of a file from its pathname in a dialog box is:

Syntax:

display dialog name of (info for "/path/to/file")

Example (using the pathname in your question):

display dialog name of (info for "/Users/mainuser/Desktop/Test/shot.png")
2
  • 1
    Really awesome answer! Just a little subquestion. I am struggling with the reasoning behind using (POSIX file "url" as alias). What exactly does POSIX do and why use alias at the end?
    – sanjihan
    Apr 29, 2016 at 14:12
  • You do not necessarily need to use the first form I presented. The second form. set fileName to name of (info for "/path/to/file") works without the need of POSIX file and as alias. Because the comments have a 600 character limit it is difficult to explain the differences and reasons why one might use one way over the other and this is better left to the User educating themselves via reading the AppleScript Language Guide PDF and other books on AppleScript. The short answer is because it works. :) Apr 29, 2016 at 14:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .