0

I'm having issues with iterating through an array passed as an argument to a function in my bash script. I thought the answer to this question would solve my issue, but I'm getting a different error and the question is very old, so I thought I should ask a new question.

I am trying to convert this code to a function, so I can pass different parameters:

EX='WT'
declare -a SCN=('fq1' 
'fq2'
'fq3' )

for i in "${SCN[@]}"; do
    echo $i
    echo $EX'_'$i
done

This prints

fq1
WT_fq1  
fq2  
WT_fq2  
fq3  
WT_fq3

What I have tried:

function myfx(){
echo $1
MYNOR=("${!2}")
for i in ${MYNOR[@]}; do
    echo $i
    echo $1'_'$i
done
}
myfx $EX $SCN[@]

Unfortunately, all I get from this is

WT

It doesn't seem to be executing the statements within the loop.

2

1 Answer 1

0

One way to get the function working is to do this:

function myfx(){
    echo "\$1=$1 \$2=$2"
    b=$2'[@]'
    for i in "${!b}"; do
        echo "$i"
        echo "$1_$i"
    done
}

myfx "$EX" "SCN"

Note that the function is called with the value of $EX and a label SCN.

Inside the function that label is used to build an indirect token b=$2'[@]'.

Then, the indirect token is used to generate the list of values inside SCN.
Using the indirection of bash ${!b}.


A little more complex option is to use only labels to call the function:

    function myfx(){
    echo "\$1=$1 \$2=$2"
    a=${!1}
    b=$2'[@]'
    for i in "${!b}"; do
        echo "$i"
        echo "${a}_$i"
    done
}

myfx "EX" "SCN"

The only added complexity is the need for indirection on $EX.


But probably the simplest of solutions is to pass all the arguments needed:

function myfx(){
    echo "\$1=$1 \$2=$2"
    a=$1; shift
    for i do
        echo "$i"
        echo "${a}_$i"
    done
}

myfx "$EX" "${SCN[@]}"

The simple for i will iterate over all arguments, which after the shift on the line above, will be all the values of "${SCN[@]}".

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.