user3100345
user3100345

Reputation: 41

Pass a parameter from 1 function to another function for loop?

I am not sure this is doable?

But i have 2 functions

do_get_array() {
        getArray "/root/1.txt"
        for e in "${array[@]}"
        do
                do_otherfunction $e
        done

}

do_otherfunction() {
        cmd="Print Me $e"
}



getArray() {
    i=0
    while read line # Read a line
    do
        array[i]=$line
        i=$(($i + 1))
    done < $1
}

echo "cmd"

SO, passing the parameter from 1 function to the other works.. but i am not sure how to loop until it the last $e in the array? Not sure i explained it correct. It Echo's out the 1st $e but the rest dont. it just stops.

Upvotes: 0

Views: 32

Answers (1)

konsolebox
konsolebox

Reputation: 75458

It Echo's out the 1st $e but the rest dont. it just stops.

You probably meant to do the echo inside the function?

do_otherfunction() {
    cmd="Print Me $e"
    echo "$cmd"  ## Or simply echo "Print Me $e"
}

Or perrhaps you want to save all messages to the variable:

do_otherfunction() {
    cmd=${cmd}"Print Me $e"$'\n'
}

It would be inefficient though.

Just some suggestions:

function do_get_array {
    get_array "/root/1.txt"
    for e in "${array[@]}"; do
        do_other_functions "$e"
    done
}

function do_other_functions {
    echo "Print Me $e"
}

function get_array {
    if [[ BASH_VERSINFO -ge 4 ]]; then
        readarray -t array
    else
        local line i=0
        while IFS= read -r line; do
            array[i++]=$line
        done
    fi < "$1"
}

Upvotes: 1

Related Questions