If I have two lists of variables: (note in the second list, the space is the element seperator)

l1=(su1 su2 su3 su4)
l2=(1,2,3 4,3,2 4,7,6 3,2,1)

and I want to loop through both lists so that a command is executed for in the sense that su1 goes with 1,2,3, su2 goes with 4,3,2, su3 goes with 4,7,6 and su4 goes with 3,2,1

So if each element of l1 corresponds to a directory and I want to do something like:

l1=(su1 su2 su3 su4)
l2=(1,2,3 4,3,2 4,7,6 3,2,1)
for i in "${l1[@]}"
for e in "${l2[@]}"
cd $directory/$i
echo "${e}" > file.txt

In other words, cd into each directory in l1 and make a file using the corresponding element in l2

The above is what I've tried but it just makes a file using the first element of l2 in each directory in l1

  • Should the filename in the directory su1 for exmaple be 1,2,3? Or shoudl there be 3 files in su1 called 1, 2 and 3? – chaos Oct 16 '15 at 19:41
  • @chaos in su1 there should be one file called file.txt containing 1,2,3 – FakeBrain Oct 16 '15 at 19:43

Use this:

# first create those directories
mkdir "${l1[@]}"
# set counter value to 0
# loop trough the array l1 (while the counter $c is less than the length of the array $l1)
while [ "$c" -lt "${#l1[@]}" ]; do
  # echo the corresponding value of array l2 to the file.txt in the directory
  echo "${l2[$c]}" > "${l1[$c]}/file.txt"
  # increment the counter
  let c=c+1

The result:

$ cat su1/file.txt 
$ cat su2/file.txt 
$ cat su3/file.txt 
$ cat su4/file.txt 
  • Or, loop over the indices of the first array: for idx in "${!l1[@]}"; do something with "${l1[idx]}" and "${l2[idx]}"; done – glenn jackman Oct 16 '15 at 20:07
  • @glennjackman Good point didn't know that you can loop over the index values, thanks glenn! – chaos Oct 16 '15 at 20:09
  • could someone explain what -lt does ? – FakeBrain Oct 16 '15 at 20:30
  • @FakeBrain Sure, it means "less than" and is from the test utillity. For all other operators see man test – chaos Oct 16 '15 at 20:33
  • ah ok. so because I didn't specify my exact directory structure and that those directories were already made, this seemed to work for me. Of course, wouldn't have gotten it w/o your answer while [ "${c}" -lt "${#l1[@]}" ]; do cd ${dataDir}/${l1[$c]}/zstats/mni echo "${l2[$c]}" > file.txt let c=c+1 done – FakeBrain Oct 16 '15 at 21:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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