Waygood Waygood - 7 months ago 28
Bash Question

bash: put list files into a variable and but size of array is 1

I am listing the files in a directory and looping through them okay, BUT I need to know how many there are too. ${#dirlist[@]} is always 1, but for loop works?

#!/bin/bash
prefix="xxx"; # as example

len=${#prefix}; # string length
dirlist=`ls ${prefix}*.text`;
qty=${#dirlist[@]}; # sizeof array is always 1
for filelist in $dirlist
do
substring="${filelist:$len:-5}";
echo "${substring}/${qty}";
done


I have files xxx001.text upto xxx013.text

but all I get is 001/1 002/1 003/1

Answer
dirlist=`ls ${prefix}*.text`

doesn't make an array, it makes a only a string with space separated file names.

you have to do

dirlist=(`ls ${prefix}*.text`)

to make it an array.

Then $dirlist will reference only the first element, you have to use

${dirlist[*]}

to reference all of them in the loop.

Comments