Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass multiple parameters to function, one being an array, another being a variable with spaces

I need to send multiple parameters to a function in bash. Parameters will be variables with spaces, or arrays

PROBLEM:

I keep getting bad substitution when trying to call my input parameter array in the function. I Also bash does not process the first parameter correctly and only displays up to the space.
How can I pass these two types of parameters to a function and utilize them properly in the function?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is my code:

#!/bin/bash

arr_conf=()

output(){
    echo $1
    for i in "${2[@]}";do
        echo $i
    done
}

arr_conf=(
"a=1"
"b=2"
"c=3"
)

name="Mr. Test"
output $name "${arr_conf[@]}"

Here is the output:

$ ./test.sh
Mr.
./test.sh: line 7: ${$1[@]}: bad substitution

>Solution :

Double quote the variable. Use shift to remove the first argument from the positional parameters.

#! /bin/bash
output(){
    echo "$1"

    shift
    for i in "$@" ; do
        echo "$i"
    done
}

arr_conf=( "a=1" "b=2" "c=3" )
name="Mr. Test"
output "$name" "${arr_conf[@]}"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading