Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a directory myDir of many .html files. I am trying to create an array of all the files in the directory so I might be able to index the array and be able to refer to particular html files in the directory. I have tried the following line:

myFileNames=$(ls ~/myDir)

for file in $myFileNames; 
#do something

but I want to be able to have a counter variable and have logic like the following:

 while $counter>=0;
   #do something to myFileNames[counter]

I am quite new to shell scripting and am unable to figure out how to achieve this hence would appreciate any help regarding this matter.

share|improve this question

2 Answers 2

You can do:

# create an array with all the filer/dir inside ~/myDir
arr=(~/myDir/*)

# iterate through array using a counter
for ((i=0; i<${#arr[@]}; i++)); do
    #do something to each element of array
    echo "${arr[$i]}"
done

You can also do this for iteration of array:

for f in "${arr[@]}"; do
   echo "$f"
done
share|improve this answer
1  
If you want to limit the number of times the for loop is run you could make the following ammendment: counter=10 for ((i=0; i<${#arr[@]} && i<counter; i++)); do –  andrew.punnett Feb 10 at 3:25
1  
Actually shopt -s nullglob can be used before array creation to avoid getting any false result. –  anubhava Feb 10 at 3:37

Your solution will work for generating the array. Instead of using a while loop, use a for loop:

#!/bin/bash
files=$( ls * )
counter=0
for i in $files ; do
  echo Next: $i
  let counter=$counter+1
  echo $counter
done
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.