arrays - 将数组传递给函数名称冲突

标签 arrays linux bash function

规范

GNU bash,版本 3.1.17(无法升级)


前提

我一直在摆弄数组,我想知道是否有任何方法可以让函数的局部变量与所述函数之外的数组同名。


例子

在下面的示例中,我将尝试显示问题

工作

#!/bin/bash
arr=(1 2 "3 4" 5)   # Make global array

myfunc()
{
    local args=("${!1}")  # Using different name for declaration
        echo ${args[@]}  # Echo new array


}
    myfunc arr[@]  # Pass array to function

输出

1 2 3 4 5

不工作

#!/bin/bash

arr=(1 2 "3 4" 5) # Create array

myfunc()
{
    local arr=("${!1}") #Not working
        echo ${arr[@]} # Not working


}
    myfunc arr[@] # Pass array to function

输出

[Blank]

原因

我想将多个数组传递给函数,但不想与传入的数组和本地数组名称发生名称冲突。


尝试过

正如您在上面看到的,我已尝试添加本地功能。我已经扫描了 bash 手册页,但似乎找不到任何其他可以提供我想要的行为的内容

Bash -x 结果

+ arr=(1 2 "3 4" 5)
+ myfunc 'arr[@]'
+ arr=("${!1}")
+ local arr
+ echo

如果需要更多信息,请告诉我。

最佳答案

恭喜您在 3.1 系列的 bash 中遇到了一个错误。

来自Bash ChangeLog在与 bash-3.2-alpha 版本相关的部分中:

This document details the changes between this version, bash-3.2-alpha, and the previous version, bash-3.1-release.

...

f. Fixed two bugs with local array variable creation when shadowing a variable of the same name from a previous context.

关于arrays - 将数组传递给函数名称冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31727410/

相关文章:

c - 将 double 组转换为字符串数组

java - 蛮力基础256乘法

linux - 当我在 Linux 终端中执行 "Recipe for target ' 时,“"make xconfig"gconfig'失败”是什么意思?

linux - cURL:如果状态为200,如何返回0?

linux - rsync 不同步文件名中的大写/小写。我怎样才能让它同步上限?

javascript - jQuery 排序功能无法正常工作

javascript - 给定日期字符串的关联数组,找到下一个最接近的日期

linux - 将命令输出分配给变量

java - 找不到/安装 libXtst.so.6?

Bash 将日期转换为时间戳