3

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?

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

1 Answer 1

6

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[@]}"
Sign up to request clarification or add additional context in comments.

1 Comment

Ah! perfect, knew it was something simple. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.