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

Time:01-19

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

CodePudding user response:

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[@]}"
  •  Tags:  
  • Related