agarwal_achhnera
agarwal_achhnera

Reputation: 2456

how to assign output of find into array

In linux shell scripting I am trying to set the output of find into an array as below

#!/bin/bash
arr=($(find . -type -f))

but it give error as -type should contain only one character. can anybody tell me where is the issue.

Thanks

Upvotes: 5

Views: 3982

Answers (2)

chepner
chepner

Reputation: 532053

If you are using bash 4, the readarray command can be used along with process substitution.

readarray -t arr < <(find . -type f)

Properly supporting all file names, including those that contain newlines, requires a bit more work, along with a version of find that supports -print0:

while read -d '' -r; do
    arr+=( "$REPLY" )
done < <(find . -type f -print0)

Upvotes: 6

jaybee
jaybee

Reputation: 955

I suggest the following script:

#!/bin/bash
listoffiles=$(find . -type f)
nfiles=$(echo "${listoffiles}" | wc -l)
unset myarray
for i in $(seq 1 ${nfiles}) ; do
    myarray[$((i-1))]=$(echo "${listoffiles}" | sed -n $i'{p;q}')
done

Because you cannot rely on the Bash automatic array instanciation through the myarr=( one two three ) syntax, because it treats the same way all whitespaces (including spaces) it sees within its parentheses. So you have to handle the resulting multiline variable listoffiles kindof manually, what I do in the above script.

echo without the -n option prints a trailing newline at the very end of the variable, but that's fine in our case because find doesn't (you may check this with echo -n "${listoffiles}").

And I use sed to extract the relevant i^th line, with the $i being interpreted by the shell before being given to sed as the first character of its own script.

Upvotes: 0

Related Questions