1

I have two arrays in a bash script, every array have same number of elements, I need to write 2nd array's every element for every element in the first array in a for loop

first array name: ARR_MPOINT

second array name: ARR_LVNAME

piece of the script:

ARR_MPOINT=(/tmp /var /log);
ARR_LVNAME=(lv_tmp lv_var lv_log)

for MPOINT in "${ARR_MPOINT[@]}"
    do
        echo "/dev/mapper/VolGroup01-${ARR_LVNAME[@]}     $MPOINT         xfs      defaults        1 2" 
    done

I need to print below output

/dev/mapper/VolGroup01-lv_tmp      /tmp        xfs      defaults        1 2
/dev/mapper/VolGroup01-lv_var      /var        xfs      defaults        1 2
/dev/mapper/VolGroup01-lv_log      /log        xfs      defaults        1 2
Ramana
  • 3
  • 5
  • 1
    A nested for loop that iterates over `ARR_LVNAME` should do the trick. Just realized you want 3 iterations instead of 9 but access both arrays at the same index. – Jonny Henly Jun 29 '17 at 05:32
  • 1
    Use a for loop like `for i in {0..$ARRAY_SIZE}`. Then something like `echo "/dev/mapper/VolGroup01-${ARR_LVNAME[i]} ${ARR_MPOINT[i]} ..."` – Jonny Henly Jun 29 '17 at 05:39
  • How can I edit ${ARR_LVNAME[@]} ? – Ramana Jun 29 '17 at 05:42
  • Have a look at this answer: https://stackoverflow.com/questions/17403498/iterate-over-two-arrays-simultaneously-in-bash – m13r Jun 29 '17 at 05:43

2 Answers2

1

If the arrays have the same length you can access the elements by index:

for ((i=0; i<${#ARR_MPOINT[@]}; i++)); do
    echo "/dev/mapper/VolGroup01-${ARR_LVNAME[i]}     ${ARR_MPOINT[i]}         xfs      defaults        1 2" 
done
mata
  • 67,110
  • 10
  • 163
  • 162
0

You could replace / with lv_ and only use the first array to get the output:

for MPOINT in "${ARR_MPOINT[@]}"; do
    echo "/dev/mapper/VolGroup01-${MPOINT//\//lv_} $MPOINT xfs defaults 1 2" 
done
m13r
  • 2,458
  • 2
  • 29
  • 39