Fabio B.
Fabio B.

Reputation: 9400

populate and read an array with a list of filenames

Trivial question.

#!/bin/bash

if test -z "$1"
then
  echo "No args!"
  exit
fi

for newname in $(cat $1); do
  echo $newname
done

I want to replace that echo inside the loop with array population code. Then, after the loop ends, I want to read the array again and echo the contents. Thanks.

Upvotes: 3

Views: 7274

Answers (3)

l0b0
l0b0

Reputation: 58828

declare -a files
while IFS= read -r
do
    files+=("$REPLY") # Array append
done < "$1"
echo "${files[*]}" # Print entire array separated by spaces

cat is not needed for this.

Upvotes: 2

Diego Sevilla
Diego Sevilla

Reputation: 29021

If the file, as your code shows, has a set of files, each in one line, you can assign the value to the array as follows:

array=(`cat $1`)

After that, to process every element you can do something like:

for i in ${array[@]} ; do echo "file = $i" ; done

Upvotes: 5

Nobwyn
Nobwyn

Reputation: 8685

#!/bin/bash

files=( )
for f in $(cat $1); do
    files[${#files[*]}]=$f
done

for f in ${files[@]}; do
    echo "file = $f"
done

Upvotes: 1

Related Questions