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

如何将JSON路径数组展开为fswatch的命令行参数?

fswatch无法正确识别从JSON读取的多路径参数

环境配置

config.json

{
    "paths": ["/Users/First Folder", "/Users/Second Folder"]
}

test.sh

#!/bin/zsh
monitored_paths=$(jq -r '.paths[]' config.json)
fswatch --verbose "${monitored_paths[@]}"

问题现象

执行上述脚本后,输出为:

start_monitor: Adding path: /Users/First Folder
/Users/Second Folder

但预期应该是两个路径都被作为独立参数添加监控:

start_monitor: Adding path: /Users/First Folder
start_monitor: Adding path: /Users/Second Folder

实际只有第一个路径被正确监控,第二个路径未被fswatch识别为独立目标。

解决方法

问题根源是直接用=$(...)赋值时,jq输出的两行路径会被合并成单个字符串,而非数组元素。"${monitored_paths[@]}"展开时,本质上只传递了一个带换行的参数给fswatch,导致第二个路径被误解析。

修改脚本为以下方式之一即可:

方法1:用readarray读取为数组(推荐,更安全)

#!/bin/zsh
readarray -t monitored_paths < <(jq -r '.paths[]' config.json)
fswatch --verbose "${monitored_paths[@]}"

方法2:用zsh数组直接赋值(简单但需注意特殊字符)

#!/bin/zsh
monitored_paths=($(jq -r '.paths[]' config.json))
fswatch --verbose "${monitored_paths[@]}"

说明

  • readarray -t会将jq输出的每一行作为数组的独立元素,-t参数自动移除每行末尾的换行符,完全适配路径的输出格式,且能处理包含空格、特殊字符的路径。
  • 进程替换< <(command)让readarray直接读取jq的输出,避免了字符串转换带来的参数合并问题。

内容的提问来源于stack exchange,提问作者F. Zer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 02:43:20