使用 -print0 将查找的输出存储在变量中
Store output of find with -print0 in variable
我在 macOS 上使用 find . -type f -not -xattrname "com.apple.FinderInfo" -print0
创建文件列表。我想存储该列表并能够将其传递给脚本中的多个命令。但是,我不能使用 tee 因为我需要它们是顺序的并等待每个完成。我遇到的问题是,由于 print0 使用空字符,如果我将它放入变量中,那么我不能在命令中使用它。
这有点冗长,但适用于默认 bash 3.2:
eval "$(find ... -print0 | xargs -0 bash -c 'files=( "$@" ); declare -p files' bash)"
现在 files
数组应该存在于您当前的 shell 中。
您需要使用 "${files[@]}"
扩展变量(包括引号)以传递文件列表。
将以 0 分隔的数据加载到 shell 数组中(比尝试在单个字符串中存储多个文件名要好得多):
bash
4.4 或更新版本:
readarray -t -d $'[=10=]' files < <(find . -type f -not -xattrname "com.apple.FinderInfo" -print0)
some_command "${files[@]}"
other_command "${files[@]}"
年长 bash
,并且 zsh
:
while read -r -d $'[=11=]' file; do
files+=("$file")
done < <(find . -type f -not -xattrname "com.apple.FinderInfo" -print0)
some_command "${files[@]}"
other_command "${files[@]}"
我在 macOS 上使用 find . -type f -not -xattrname "com.apple.FinderInfo" -print0
创建文件列表。我想存储该列表并能够将其传递给脚本中的多个命令。但是,我不能使用 tee 因为我需要它们是顺序的并等待每个完成。我遇到的问题是,由于 print0 使用空字符,如果我将它放入变量中,那么我不能在命令中使用它。
这有点冗长,但适用于默认 bash 3.2:
eval "$(find ... -print0 | xargs -0 bash -c 'files=( "$@" ); declare -p files' bash)"
现在 files
数组应该存在于您当前的 shell 中。
您需要使用 "${files[@]}"
扩展变量(包括引号)以传递文件列表。
将以 0 分隔的数据加载到 shell 数组中(比尝试在单个字符串中存储多个文件名要好得多):
bash
4.4 或更新版本:
readarray -t -d $'[=10=]' files < <(find . -type f -not -xattrname "com.apple.FinderInfo" -print0)
some_command "${files[@]}"
other_command "${files[@]}"
年长 bash
,并且 zsh
:
while read -r -d $'[=11=]' file; do
files+=("$file")
done < <(find . -type f -not -xattrname "com.apple.FinderInfo" -print0)
some_command "${files[@]}"
other_command "${files[@]}"