Mav2287
Mav2287

Reputation: 876

Store output of find with -print0 in variable

I am on macOS and using find . -type f -not -xattrname "com.apple.FinderInfo" -print0 to create a list of files. I want to store that list and be able to pass it to multiple commands in my script. However, I can't use tee because I need them to be sequential and wait for each to complete. The issue I am having is that since print0 uses the null character if I put it into a variable then I can't use it in commands.

Upvotes: 0

Views: 416

Answers (2)

Shawn
Shawn

Reputation: 52569

To load 0-delimited data into a shell array (Much better than trying to store multiple filenames in a single string):

bash 4.4 or newer:

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

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

Older bash, and zsh:

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[@]}"

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 247062

This is a bit verbose, but works with the default bash 3.2:

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

Now the files array should exist in your current shell.

You will want to expand the variable with "${files[@]}" including the quotes, to pass the list of files.

Upvotes: 1

Related Questions