bashfor-loopwhile-loop

Bash Script While Loop from two files


Im trying to do the below:

file1:

x.x.x.5
x.x.x.6

file2:

router
switch

Trying to loop through both files to create two additional files each name in file2 as:

ping_router.sh

sudo /sbin/mtr -rn -c 30 --interval 1 -Z 1 x.x.x.6 | sed 's/Start: //g' |  sed -e '2,$ s/^/     /'

ping_switch.sh

sudo /sbin/mtr -rn -c 30 --interval 1 -Z 1 x.x.x.7 | sed 's/Start: //g' |  sed -e '2,$ s/^/     /'

Script:

for x in $(cat file1); do; for z in $(cat file2); do; echo "sudo /sbin/mtr -rn -c 30 --interval 1 -Z 1 $x | sed 's/Start: //g' |  sed -e '2,$ s/^/     /'" >>mtr_$z.sh; done;done

^^ It creates the two files but includes both IPs

How would i accomplish the above?


Solution

  • With bash:

    #!/bin/bash
    
    declare -A data1 data2        # associative arrays
    declare -i counter1 counter2  # integer flag
    
    # read file1 to associative array data1
    while read -r line; do
      counter1+=1; data1[$counter1]="$line"
    done < file1
    
    # read file2 to associative array data2
    while read -r line; do
      counter2+=1; data2[$counter2]="$line"
    done < file2
    
    # print associative arrays
    for i in ${!data1[@]}; do
      echo "foo ${data1[$i]} bar >ping_${data2[$i]}.sh"
      echo "foo ${data1[$i]} bar" >"ping_${data2[$i]}.sh"
    done
    

    Output:

    foo x.x.x.6 bar >ping_switch.sh
    foo x.x.x.5 bar >ping_router.sh