【问题标题】:Store output of find with -print0 in variable使用 -print0 将 find 的输出存储在变量中
【发布时间】:2021-09-07 11:24:32
【问题描述】:

我在 macOS 上使用 find . -type f -not -xattrname "com.apple.FinderInfo" -print0 创建文件列表。我想存储该列表并能够将其传递给我的脚本中的多个命令。但是,我不能使用 tee 因为我需要它们是连续的并等待每个完成。我遇到的问题是,由于 print0 使用空字符,如果我将它放入变量中,那么我不能在命令中使用它。

【问题讨论】:

  • 您使用的是哪个外壳? zsh、OS X 自带的古代 bash、现代 bash 还是 posix sh?
  • 我正在使用 ZSH 和 Big Sur
  • @Mab2287:你为什么使用-print0?我只是将它们放入一个数组中:files=( $(find . -type f -not -xattrname "com.apple.FinderInfo") )
  • 我试过了,但是里面有空格和特殊字符,所以会窒息

标签: macos shell zsh


【解决方案1】:

要将 0 分隔的数据加载到 shell 数组中(比尝试将多个文件名存储在单个字符串中要好得多):

bash 4.4 或更新版本:

readarray -t -d $'\0' files < <(find . -type f -not -xattrname "com.apple.FinderInfo" -print0)

some_command "${files[@]}"
other_command "${files[@]}"

bashzsh

while read -r -d $'\0' file; do
    files+=("$file")
done < <(find . -type f -not -xattrname "com.apple.FinderInfo" -print0)

some_command "${files[@]}"
other_command "${files[@]}"

【讨论】:

  • 如果你想一次处理一个文件,而不是一次将所有文件名传递给命令,只需使用在循环内运行这些命令而不是填充的第二个版本一个数组。
【解决方案2】:

这有点冗长,但适用于默认的 bash 3.2:

eval "$(find ... -print0 | xargs -0 bash -c 'files=( "$@" ); declare -p files' bash)"

现在files 数组应该存在于您当前的 shell 中。

您需要使用包含引号的"${files[@]}" 扩展变量,以传递文件列表。

【讨论】:

  • 如何清除 ${files[@]} 以便每次运行时都不会拒绝已经存在的数据?
  • 我不明白你在问什么。是否与您在问题中未描述的某些过程有关?
  • 我想通了。我在循环中使用它,即使再次运行此命令后,第二次迭代仍然具有$files 中的原始值。解决方案是将unset files 放在此命令上方,以确保每次迭代都有空白。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-10
  • 1970-01-01
  • 1970-01-01
  • 2014-07-02
  • 1970-01-01
  • 2015-05-03
  • 1970-01-01
相关资源
最近更新 更多