Monday, April 11, 2022

[SOLVED] How to use $1 in ${} in shell script

Issue

function print_array(){
    NUMBER=1
    for i in ${$1[@]}; do
        printf "%d: %s \n" $NUMBER $i
        $((NUMBER++))
    done
}

I want to write a function that can accept an array as a parameter and print all things inside the array.

So I wrote something like ${$1[@]}, and shell said that's a "bad substitution".

Any ways to achieve the same effect? Thanks!


Solution

There are several problems with this code, but the primary is one is that $1 will never be an array. If you want to pass an array to a function, you would need to do something like this:

print_array(){
    NUMBER=1
    for i in "${@}"; do
        printf "%d: %s \n" $NUMBER "$i"
        ((NUMBER++))
    done
}

myarray=(this is "a test" of arrays)
print_array  "${myarray[@]}"

This will output:

1: this 
2: is 
3: a test 
4: of 
5: arrays 

Note that the quoting in this script is critical: Writing ${myarray[@]} is not the same as writing "${myarray[@]}"; see the Arrays section of the bash manual for details, as well as the Special Parameters section for information about $@ vs "$@".



Answered By - larsks
Answer Checked By - Marie Seifert (WPSolving Admin)