shell 如何将Bash数组作为参数扩展到`fswatch`?

fafcakar  于 8个月前  发布在  Shell
关注(0)|答案(2)|浏览(73)

下面是我的设置的细节。我有以下文件:

config.json

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

test.sh

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

JSON数组中的paths键需要由jq处理,然后扩展为参数。然而,当执行test.sh时,我遇到了以下输出:
输出量:

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

我的期望是:

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

总之,我的目标是监视两个文件,但似乎只监视了一个文件。如何解决此问题?
编辑:
在注解中按请求使用精确输出。

kx5bkwkv

kx5bkwkv1#

**注:**以下答案基于最初归因于问题的bash标签;标签已更改为zsh;我不使用zsh,但从OP的评论:

  • while/read循环在zsh中工作
  • mapfilezsh中不工作

正如注解中提到的,当前monitored_paths赋值使用单个(2行)字符串填充变量:

$ typeset -p monitored_paths
declare -a monitored_paths=([0]=$'/Users/First Folder\n/Users/Second Folder')

请注意两个路径之间的嵌入式换行符(\n)。
这整个两行结构作为一条路径被馈送到fswatch
monitored_paths填充为数组的几个选项:

while/read循环:

monitored_paths=()

while read -r path
do
    monitored_paths+=("$path")
done < <(jq -r '.paths[]' config.json)

Map文件:

mapfile -t monitored_paths < <(jq -r '.paths[]' config.json)

这两种方法都可以创建/填充数组:

$ typeset -p monitored_paths
declare -a monitored_paths=([0]="/Users/First Folder" [1]="/Users/Second Folder")

从这里开始,OP的当前代码应该按预期运行:

fswatch --verbose "${monitored_paths[@]}"
mrfwxfqh

mrfwxfqh2#

在shell语法从shebang你的例子

#!/bin/zsh
typeset -a monitored_paths
jq -r '.paths[]' config.json | while read -r p; do monitored_paths+="$p"; done
fswatch --verbose $monitored_paths

相关问题