Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0125· openaiHugging Face Suzhen/CodeChat

write a bash function that passes an array to another bash function

  1. User

    write a bash function that passes an array to another bash function

  2. Assistant

    Here is an example of a bash function that passes an array to another bash function:

    #!/bin/bash
    
    my_function() {
        local my_array=("$@")
        for element in "${my_array[@]}"
        do
            echo "$element"
        done
    }
    
    pass_array() {
        local my_array=("apple" "banana" "cherry")
        my_function "${my_array[@]}"
    }
    
    pass_array
    

    In this example, the pass_array function creates an array called my_array containing three strings. It then calls the my_function function and passes the elements of my_array as arguments by using "${my_array[@]}". The my_function function then receives the array as a parameter and prints each element of the array.