简体   繁体   English

Bash函数可在多行上打印数组

[英]Bash function to print array on multiple lines

I wrote this function to print arrays in bash without using that horrible bracket syntax: 我编写了此函数来使用bash打印数组,而不使用那种可怕的括号语法:

printarr()
{
     arr=$1      # first argument
     printf '%s\n' "${arr[@]}"
}

Does not work as expected. 不能按预期工作。

It will print out the first array you feed it, but then if you feed it another array it will print out the first one again. 它会打印出您喂入的第一个数组,但是如果您喂入另一个数组,则会再次打印出第一个数组。

I call it like this 我这样称呼它

$ arr=( "single" "line" "arr" )
$ printarr $arr
$ multiarr=( "multi"
> "line"
> "arr")
$ printarr $multiarr

GNU bash, version 3.2.25(1)-release GNU bash版本3.2.25(1)-发布

If you don't want to use brackets when sending the array to the function, send just its name and use indirect expansion: 如果在将数组发送给函数时不想使用方括号,则仅发送其名称并使用间接扩展:

#! /bin/bash
printarr()
{
     arr=$1'[@]'
     printf '%s\n' "${!arr}"
}

arr1=( "single" "line" "arr with spaces" )
arr2=( "SINGLE" "LINE" "ARR WITH SPACES" )

printarr arr1
printarr arr2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM