Home > OS >  Use itterator inside array name
Use itterator inside array name

Time:11-20

I am trying to iterate and use the variable i inside another variable.

I have three arrays, when iterating I want to specify the correct variable name of the array I am referencing. How do I do this in bash?

CONTAINER_1_FILES=()
CONTAINER_2_FILES=()
CONTAINER_3_FILES=()

  for ((i=1; i <= 3; i  ))
  do
    CURRENT_CONTAINER=("${CONTAINER_$i_FILES[@]}") # I am trying to use $i here
    echo ${CURRENT_CONTAINER[@]}
  done

CodePudding user response:

If using Bash >=4.2, nameref variables will do what you need:

#!/usr/bin/env bash

container_1_files=(foo1 bar1 baz1)
container_2_files=(foo2 bar2 baz2 quux)
container_3_files=(foo3 bar3)

containers=(container_1 container_2 container_3)

for container in "${containers[@]}"; do
  declare -n container_files="${container}_files"
  printf 'Files from %s:\n' "$container"
  printf '%s\n' "${container_files[@]}"
done

Output:

Files from container_1:
foo1
bar1
baz1
Files from container_2:
foo2
bar2
baz2
quux
Files from container_3:
foo3
bar3

Now if you are going to reference files for containers, then place or link these files into actual filesystem directories, rather than trying to replicate a folder/files hierarchy into Bash arrays and dynamic variable names.

As a bonus, it will even works with a POSIX shell grammar:

#!/usr/bin/env sh

mkdir -p -- container_1 container_2 container_3
cd container_1 && { touch foo1 bar1 baz1;} && cd .. || exit
cd container_2 && { touch foo2 bar2 baz2 quux;} && cd .. || exit
cd container_3 && { touch foo3 bar3;} && cd .. || exit

for container in ./container_*; do
  printf 'Files from %s:\n' "$container"
  for file in "$container/"*; do
    printf '%s\n' "${file##*/}"
  done
done

CodePudding user response:

#! /bin/bash

declare -a CONTAINER_1_FILES=(a b c)
declare -a CONTAINER_2_FILES=(d e f)
declare -a CONTAINER_3_FILES=(g h i)
declare -a CURRENT_CONTAINER=()

for ((i=1; i <= 3; i  )); do
    declare -n CURRENT_CONTAINER_REF="CONTAINER_${i}_FILES"
    CURRENT_CONTAINER=(${CURRENT_CONTAINER_REF[@]})
    echo "DECLARATION:${CURRENT_CONTAINER[@]@A}"
    echo "VALUES ... :${CURRENT_CONTAINER[@]}"
done
  •  Tags:  
  • bash
  • Related