mles
mles

Reputation: 3456

loop over files in a bash script

I want to edit a bunch of files with a bash script. First I need the single path to the file as well as a counter. So far I came up with this:

let n=0
array=(`pwd`"/worker/worker*/conf/logfilefilter-worker*.xml")
for i in "${array[@]}"; do
  let "c += 1"
  echo $i
  echo $c
  # here comes the edit stuff.
done

But this loop just runs once:

[mles@sagnix etl-i_test]$ ./iprog_new --test
/home/devel/mles/etl-i_test/worker/worker01/conf/logfilefilter-worker01.xml     /home/devel/mles/etl-i_test/worker/worker02/conf/logfilefilter-worker02.xml /home/devel/mles/etl-i_test/worker/worker03/conf/logfilefilter-worker03.xml /home/devel/mles/etl-i_test/worker/worker04/conf/logfilefilter-worker04.xml /home/devel/mles/etl-i_test/worker/worker05/conf/logfilefilter-worker05.xml /home/devel/mles/etl-i_test/worker/worker06/conf/logfilefilter-worker06.xml /home/devel/mles/etl-i_test/worker/worker07/conf/logfilefilter-worker07.xml /home/devel/mles/etl-i_test/worker/worker08/conf/logfilefilter-worker08.xml
1

How will the loop run one by one trough the files?

Upvotes: 1

Views: 787

Answers (1)

Jens
Jens

Reputation: 72629

This

array=(`pwd`"/worker/worker*/conf/logfilefilter-worker*.xml")

is just one element, because file name globbing (for *) is supressed in quoted strings. Then in "${array[@]}" the single element gets glob expanded but due to the double quotes remains as a single string with all filenames separated by spaces. Does

array=(`pwd`/worker/worker*/conf/logfilefilter-worker*.xml)

or

for i in ${array[@]}; do  # no double quotes

work better? On the other hand, what about a more portable solution without bashims like arrays? The canonical way to iterate over files is

for file in $PWD/worker/worker*/conf/logfilefilter-worker*.xml; do
   echo "$file"
done

Upvotes: 5

Related Questions