将find的输出与-print0一起存储在变量中



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

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

bash4.4或更新版本:

readarray -t -d $'' files < <(find . -type f -not -xattrname "com.apple.FinderInfo" -print0)
some_command "${files[@]}"
other_command "${files[@]}"

较旧的bashzsh:

while read -r -d $'' file; do
files+=("$file")
done < <(find . -type f -not -xattrname "com.apple.FinderInfo" -print0)
some_command "${files[@]}"
other_command "${files[@]}"

这有点冗长,但可以与默认的bash 3.2:一起使用

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

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

您将希望用包含引号的"${files[@]}"展开变量,以传递文件列表。

最新更新