单变量分配到一个数组(的地方) [英] Assign single variable to an array (in place)

查看:88
本文介绍了单变量分配到一个数组(的地方)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下code:

  A =(1 2 3)
A =七出口
声明-p一

输出(从声明)是:

 声明-ax一个=([0] =七[1] =2[2] =3)

所以 A 是一个数组。问题:


  1. 如何更改第二行,所以​​ A 不会是一个数组了,但一个简单的变量的值 7 ?我在寻找一个班轮,不用取消设置

  2. 分配一个变量数组只替换第一个元素,而不是整个数组。哪里是这种行为规定?

请注意:猛砸v 3.2.48(OS X)

(我已经回答 今天这个问题,这让我在思考这个问题,我正在寻找一个更清洁的解决方案)。


编辑:我在寻找一个:

  A =(1 2 3)/ *这里一号线请:) * /
取消设置
A =七出口
声明-p一

但没有做明确的取消设置。要紧的是一个特殊的情况下,当 A ,其实是 PATH 变量(见的this 问题)。


解决方案

您需要使用取消设置

从手动(如下)的第一次报价会解释说,在说:

  A =七

A 是一个数组较早的相同以说:

  A [0] =七

手动


  

当分配给索引数组,如果可选的下标
  提供的,该索引将分配给;否则的索引
  分配元件是由语句加上分配给最后一个索引
  一。索引从零开始。




  

取消设置内置的是用来摧毁阵列。 取消设置名称[下标]
  在破坏指数数组元素的下标的。必须小心,以
  避免因文件名扩展不必要的副作用。未设置名称,
  其中name是一个数组,删除整个阵列。的 A标'*'
  或'@'还删除整个数组。


Consider following code:

a=(1 2 3)
a='seven'

export a
declare -p a

The output (from declare) is:

declare -ax a='([0]="seven" [1]="2" [2]="3")'

So a is an array. Questions:

  1. How to change second line, so a will not be an array anymore, but a simple variable with the value seven? I'm looking for a one-liner, without unset etc.
  2. Assigning an variable to the array replaces only first element, not the whole array. Where is this behaviour specified?

Note: Bash v. 3.2.48 (OS X).

(I've answered this question today, which got me thinking on this problem, and I'm looking for a cleaner solution).


Edit: I'm looking for a:

a=(1 2 3)

/* One line here please :) */
unset a
a='seven'

export a
declare -p a

but without doing explicit unset. It matters in a special case when a is in fact a PATH variable (see this question).

解决方案

You need to use unset.

The first quote from the manual (given below) would explain that upon saying:

a='seven'

when a was an array earlier is identical to saying:

a[0]='seven'

Quoting from the manual:

When assigning to indexed arrays, if the optional subscript is supplied, that index is assigned to; otherwise the index of the element assigned is the last index assigned to by the statement plus one. Indexing starts at zero.


The unset builtin is used to destroy arrays. unset name[subscript] destroys the array element at index subscript. Care must be taken to avoid unwanted side effects caused by filename expansion. unset name, where name is an array, removes the entire array. A subscript of ‘*’ or ‘@’ also removes the entire array.

这篇关于单变量分配到一个数组(的地方)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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