You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行含if语句的bash脚本时~被识别为未知令牌如何解决

问题解答

错误提示:Expected “,” or “]” but found unknown token

你遇到的报错核心原因是用AppleScript运行环境执行Shell脚本代码,两类脚本的语法体系完全不兼容,才会触发语法错误。

具体报错原因

你代码里高亮的~是Shell(Bash/Zsh等macOS默认终端脚本环境)专属的当前用户目录占位符,AppleScript语法体系没有对这个符号的定义,所以解析时会把它识别为未知Token,触发上述报错。你贴的这段代码本身是合法的Shell脚本,语法没有问题。

解决方案

方案1:直接用Shell环境运行

把这段代码复制到macOS自带的「终端」App中执行即可,完全可以实现判断用户资源库下的Desktop Pictures目录是否存在、不存在则创建的逻辑。

方案2:转换为AppleScript语法执行

如果你需要在AppleScript中实现相同逻辑,可选用以下两种写法:

  1. AppleScript调用Shell执行原有逻辑:
do shell script "if [ -d ~/Library/Desktop\\ Pictures/ ]; then echo \"Desktop Pictures directory already exists\"; else mkdir ~/Library/Desktop\\ Pictures/; fi"
  1. 纯AppleScript原生实现(无需调用Shell):
set userLibraryPath to POSIX path of (path to library folder from user domain)
set targetFolderPath to userLibraryPath & "Desktop Pictures/"
tell application "Finder"
    if exists folder POSIX file targetFolderPath then
        log "Desktop Pictures directory already exists"
    else
        make new folder at folder POSIX file userLibraryPath with properties {name:"Desktop Pictures"}
    end if
end tell

内容的提问来源于stack exchange,提问作者ca11is0n

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 09:09:01