Copy a Bash array with empty elements

前端 未结 2 1620
轮回少年
轮回少年 2021-01-12 03:04

I\'m having problems in bash (ver 4.2.25) copying arrays with empty elements. When I make a copy of an array into another variable, it does not copy any empty elements alon

相关标签:
2条回答
  • 2021-01-12 03:45

    Starting with Bash 4.3, you can do this

    $ alpha=(bravo charlie 'delta  3' '' foxtrot)
    
    $ declare -n golf=alpha
    
    $ echo "${golf[2]}"
    delta  3
    
    0 讨论(0)
  • 2021-01-12 04:02

    You have a quoting problem and you should be using @, not *. Use:

    copy=( "${array[@]}" )
    

    From the bash(1) man page:

    Any element of an array may be referenced using ${name[subscript]}. The braces are required to avoid conflicts with pathname expansion. If subscript is @ or *, the word expands to all members of name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS special variable, and ${name[@]} expands each element of name to a separate word.

    Example output after that change:

    --- array (3) ---
    one
    
    three
    
    --- copy (3) ---
    one
    
    three
    
    0 讨论(0)
提交回复
热议问题