Nikhil
Nikhil

Reputation: 586

Bash Script : Passing array as an argument to a function and printing the array

I am passing an array to a function and trying to print each and every element of the array.

Below is the code snippet with quotes around the array parameter:

#!/bin/bash

print_array ()
{
        array=$@
        for i in "${array[@]}" #with quotes
        do
                echo $i
        done
}

ar=("1. a" "2. b" "3. c")
print_array ${ar[@]}

When I execute the above script, the output is

1. a 2. b 3. c

Below is the code snippet without quotes around the array parameter:

#!/bin/bash

print_array ()
{
        array=$@
        for i in ${array[@]} #without quotes
        do
                echo $i
        done
}

ar=("1. a" "2. b" "3. c")
print_array ${ar[@]}

When I execute the above script, the output is

1.
a
2.
b
3.
c

The output varies according to the quotes around the array parameter. I am really confused with the output displayed. Please help me out to resolve it.

The expected output should be :

1. a
2. b
3. c

Upvotes: 0

Views: 852

Answers (2)

ajaaskel
ajaaskel

Reputation: 1699

#!/bin/bash

print_array ()
{
    array=("$@")
    for i in "${array[@]}"
    do
            echo "$i"
    done
}

ar=("1. a" "2. b" "3. c")
print_array "${ar[@]}"

Result:

1. a
2. b
3. c

Using =() during assignment keeps the variable as an array.

Upvotes: 0

William Pursell
William Pursell

Reputation: 212208

#!/bin/bash

print_array ()
{
        for i;
        do
                printf "%s\n" "$i"
        done
}

ar=("1. a" "2. b" "3. c")
print_array "${ar[@]}"  # with quotes

If you want to be explict, you can write for i in "$@"

You can also write:

#!/bin/bash

print_array ()
{
        array=("$@")
        for i in "${array[@]}"; do
                printf "%s\n" "$i"
        done
}

ar=("1. a" "2. b" "3. c")
print_array "${ar[@]}"  # with quotes

Upvotes: 2

Related Questions