Issue
I am trying to use the bash to loop through an unknown number of folders which end with a progressive number starting from 0. Each folder is named processor* where * stands for the progressive number (e.g. processor0, processor1, processor2, etc..). Inside each loop the script should execute these commands find ./ -name 'U' | while read U ; do cp "$U" ./0 ; done
.
My for loop looks like this:
for i in processor*; do
cd ./processor$i
find ./ -name 'U' | while read U ; do cp "$U" ./0 ; done
cd ..
done
but it currently does not work.
Solution
When you use the syntax for i in processor*
, the results of expanding processor*
will be iterated over, and the variable i
will hold the result for a given iteration.
From the GNU HTML manual for bash:
The syntax of the
for
command is:
for name [ [in [words …] ] ; ] do commands; done
Expandwords
(see Shell Expansions), and execute commands once for each member in the resultant list, withname
bound to the current member.
For example, if the current working directory contained the directories processor0
, processor1
, and processor_something_else
, and the expansion of processor*
was in that order, then i
will have the following value for the separate iterations:
i
has the valueprocessor0
in the first iterationi
has the valueprocessor1
in the second iterationi
has the valueprocessor_something_else
in the second iteration
The expression ./processor$i
then would evaluate to the following in each iteration:
./processorprocessor0
./processorprocessor1
./processorprocessor_something_else
This is because the value of i
will be expanded as the cd
command is generated.
What you really want is to use cd ./"$i"
.
Answered By - Shane Bishop