AppleScript中字符串、别名与POSIX路径的使用场景及转换疑问
核心问题解答
你拼接出来的readmePath是Mac风格的冒号分隔路径(比如Macintosh HD:Users:你的用户名:Documents:README.md),这种格式是AppleScript和Finder等原生macOS应用的“母语”,但shell命令(比如touch)属于Unix环境,只认斜杠分隔的POSIX路径(比如/Users/你的用户名/Documents/README.md)——直接把冒号路径传给shell,它根本识别不了,所以必须用POSIX path of转换格式,才能让touch找到正确的位置。
三种路径类型的适用场景
Mac风格字符串路径
格式:用冒号:分隔层级,比如Macintosh HD:Users:test:Desktop:
适用场景:和Finder、System Events等原生AppleScript应用交互时使用,比如脚本里的exists file readmePath、reveal file readmePath,这些都是Finder的命令,完全兼容这种格式。别名(Alias)
本质:是指向文件/文件夹的动态指针,就算文件被移动到其他位置,只要系统能追踪到,别名依然能定位到目标文件
适用场景:需要持久化指向某个文件,或者要确保路径始终有效时使用。比如:set myFile to alias "Macintosh HD:Users:test:Notes.txt"POSIX路径
格式:斜杠/分隔的Unix风格路径,比如/Users/test/Desktop/
适用场景:所有通过do shell script调用的shell命令(比如touch、mkdir、cp等),因为shell是Unix环境,只认这种路径格式。
你的脚本拆解
set currentFolder to target of front window as string从Finder获取的是当前窗口文件夹的Mac风格字符串路径- 拼接成
readmePath后,这个格式Finder能识别,所以exists file readmePath可以正常判断文件是否存在 - 但
do shell script调用touch时,必须把Mac风格路径转成POSIX格式,否则shell无法解析路径,导致命令执行失败。
原生写法优化(无需POSIX转换)
其实不用调用shell,直接用Finder的原生命令创建文件更简单:
tell application "Finder" set currentFolder to target of front window set readmeFile to currentFolder & "README.md" as alias if not (exists readmeFile) then make new file at currentFolder with properties {name:"README.md"} reveal readmeFile else display dialog "README.md already exists in this folder." end if end tell
内容的提问来源于stack exchange,提问作者dufei

