将参数从1个函数传递给另一个函数进行循环?

时间:2022-08-19 11:48:44

I am not sure this is doable?

我不确定这是可行的吗?

But i have 2 functions

但我有2个功能

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.

所以,将参数从1个函数传递到另一个函数..但是我不知道如何循环直到它在数组中的最后一个$ e?不确定我解释正确。 Echo是第一个$ e,但其余的不是。它就停止了。

1 个解决方案

#1


1  

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

Echo是第一个$ e,但其余的不是。它就停止了。

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"
}

#1


1  

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

Echo是第一个$ e,但其余的不是。它就停止了。

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"
}