1

How can I run for loop with two variables or in other words is it acceptable to do that? I will clarify my question by the following example:

I have a list of letters included in a text file "names.txt" and I have numbers included in text file "numbers.txt" each number in "numbers.txt" is equal to letter in "names.txt" (row by row) I want to create folders has the names in names.txt + the numbers in numbers.txt

names.txt       numbers.txt         output_folder name
A               1                   A1
B               2                   B2
C               3                   C3
D               4                   D4
E               5                   E5

to create folders has the names included in names.text I can use the following code:

#!/bin/bash
in=/in/on/an
out=/ss/tt/nn
for i in $(cat $in/names.txt); do
 mkdir ${in}/${i}
done

How can I add a second variable to a for loop i.e in the previous code we have the variable i is belonging to the names.txt how can I add variable b belonging to numbers.txt?

terdon
  • 242,166

1 Answers1

0

If that's really all you need, you can just do

mkdir $(paste letters.txt numbers.txt | tr -d '\t')

That will create the directories for you. As for the general case in bash, this is usually done in a similar way:

paste letters.txt numbers.txt | while read let num; do 
    mkdir "${let}${num}" 
done

To answer your specific question, you can't run a for loop with more than one variable in bash but there are usually ways around it as you can see. The closest you can get is using arrays. For example:

let=( $(cat letters.txt) )
num=( $(cat numbers.txt) )
for((i=0;i<${#let[@]};i++)); do 
    mkdir "${let[$i]}${num[$i]}"
done
terdon
  • 242,166
  • I highly appreciate your answer. Kindly do you know any other ways to do loop for two variables –  Nov 11 '14 at 02:45
  • @dr.green it's not possible in bash. The workaround is using arrays, see update. Normally, if you need to combine variables you use a while loop instead. – terdon Nov 11 '14 at 02:46
  • Please can you explain the for .. do line of the code. Thanks –  Nov 11 '14 at 02:48
  • @dr.green see here. That construct means "for every value of $i from 0 to the number of elements in the array $let" (that's what ${#let[@]} is). It is just a way to iterate over the elements in an array. – terdon Nov 11 '14 at 02:51
  • Cool! this is great. Many thousands of thanks –  Nov 11 '14 at 02:53