复制猛砸数组空元素 [英] Copy a Bash array with empty elements

查看:121
本文介绍了复制猛砸数组空元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在bash中复制阵列,空元素的问题(版本4.2.25)。当我做一个数组的一个拷贝到另一个变量,它不会复制任何空元素与它一起。

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 along with it.

#!/bin/bash

array=( 'one' '' 'three' )
copy=( ${array[*]} )

IFS=$'\n'

echo "--- array (${#array[*]}) ---"
echo "${array[*]}"

echo
echo "--- copy (${#copy[*]}) ---"
echo "${copy[*]}"

当我这样做,这里是输出:

When I do this, here is the output:

--- array (3) ---
one

three

--- copy (2) ---
one
three

原来的数组有三个元素,包括空元素,但副本不。我在做什么错在这里?

The original array has all three elements including the empty element, but the copy does not. What am I doing wrong here?

推荐答案

您有报价的问题,你应该使用 @ ,而不是 * 。用途:

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

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

的bash(1)手册页

数组的任何元素都可以用被引用的 $ {名[下标]}
         大括号是必需的,以避免与路径扩展冲突。如果
          下标 @ * ,字扩展到所有成员的 名称 。这些
         只有当词出现在双引号内标不同。如果
         这个词是双引号, $ {名称[*]} 扩展到与一个字
         通过的第一个字符分隔每个数组成员的值在 IFS
         特殊变量,和 $ {名称[@]} 扩展中的每个元素的 名称 为一个词。

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.

这改变后的输出示例:

--- array (3) ---
one

three

--- copy (3) ---
one

three

这篇关于复制猛砸数组空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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