Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 553
Waygood Avatar asked Mar 05 '13 13:03

Waygood


People also ask

What does $@ In bash mean?

Key Points. Save commands in files (usually called shell scripts) for re-use. bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc.

What does $_ mean in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.


2 Answers

This:

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

doesn't make an array. It only makes 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, so you have to use

${dirlist[*]}

to reference all of them in the loop.

like image 112
KarelSk Avatar answered Sep 29 '22 06:09

KarelSk


You're not creating an array unless you surround it with ( ):

dirlist=(`ls ${prefix}*.text`)
like image 37
Costi Ciudatu Avatar answered Sep 29 '22 06:09

Costi Ciudatu