Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign single variable to an array (in place)

Tags:

arrays

bash

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).

like image 627
kamituel Avatar asked Jul 12 '26 01:07

kamituel


1 Answers

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.

like image 136
devnull Avatar answered Jul 13 '26 14:07

devnull



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!