0

I tried to use array elements from a loop as dynamic key for select related arrays. i tried several methods but internal loops does not work and i can't use parent argument as dynamic key for select correct array.

Any suggestion? Thank you

#!/bin/bash

SUFFIX='.zip'
ZIPCOMMAND=""
DSTDIR="/root/destfiles/"
SRCDIR="/root/srcfiles"
ZIPCOMMAND=""
PACKAGES=("STARTER" "BUSINESS")
STARTER=("209" "Module2")
BUSINESS=("210" "Module1" "Module3")

# packageid, destination command
function make_zip_file {
   targetfilename="${2}${1}$(echo -n "${1}" | md5sum | cut -d' ' -f1 ).zip ${3}"
    echo "$targetfilename"
}
cd $SRCDIR
declare -p BUSINESS
for j in "${PACKAGES[@]}"; do
    COUNT=0;
    declare -p j
    nums=${#j[@]}
    echo "$nums";
    if (( $nums > 1 )); then
        for i in "${j[@]}"; do
               if ((  $COUNT == 0 )); then
                               Packageid=$i;
                               echo -e "Package id $Packageid";
               else
                      echo -e "# $COUNT - $i$SUFFIX"
                      ZIPCOMMAND="${ZIPCOMMAND} ${i}${SUFFIX}";
                         fi
               COUNT=$(($COUNT+1));
        done
        echo -e "$ZIPCOMMAND"
        ZIPPARAMS=$(make_zip_file "$Packageid" "$DSTDIR" "$ZIPCOMMAND")
        zip -qr $ZIPPARAMS
        echo -e "$ZIPPARAMS"
    fi
done
0

1 Answer 1

2

If I understand your question, you're looking for a way to dereference the arrays STARTER and BUSINESS using the variable j.

Perhaps there's a better way, but what I do is:

jref="${j}[@]"
jarray=("${!jref}")

Example:

$ BUSINESS=("210" "Module1" "Module3")
$ j=BUSINESS
$ jref="${j}[@]"
$ jarray=("${!jref}")
$ printf "%s\n" "${jarray[@]}"
210
Module1
Module3
$ echo ${jarray[1]}
Module1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.