开发者

populate and read an array with a list of filenames

开发者 https://www.devze.com 2023-03-19 03:24 出处:网络
Trivial question. #!/bin/bash if test -z \"$1\" then echo \"No args!\" exit fi for newname in $(cat $1); do echo $newname

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

精彩评论

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

关注公众号