Bash脚本:将数组作为参数传递给函数并打印该数组 [英] Bash Script : Passing array as an argument to a function and printing the array

查看:51
本文介绍了Bash脚本:将数组作为参数传递给函数并打印该数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将数组传递给函数,并尝试打印该数组的每个元素.

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

下面是带有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.

预期输出应为:

1. a
2. b
3. c

推荐答案

#!/bin/bash

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

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

如果要公开显示,可以在"$ @"中为我写 i

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

您也可以写:

#!/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

这篇关于Bash脚本:将数组作为参数传递给函数并打印该数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆