开发者

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 开发者_StackOverflow社区and echo the contents. Thanks.


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


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.


#!/bin/bash

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜