Vicky
Vicky

Reputation: 1338

Extracting elements of an array in bash

I have an array a = ( 1 2 3 4 5 6) Now I want to extract 1 and 2nd elements of the array into two different variables and assign rest of the elements of array a to another array that will have elements only 3rd element onwards . so that b and c are the variables with 1st and second variable respectively

just as :

b=$a[0];
c=$a[1]; 

and

arr=( 3 4 5 6 )`

Upvotes: 0

Views: 1250

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 296049

$a[0] doesn't treat [0] as part of the expansion -- rather, it's a separate string to be appended. As given in the bash-hackers' wiki page on paramater expansion, you need to use curly braces to surround subscripts when extracting content from an array.


a=( 1 2 3 4 5 6 )
b=${a[0]}
c=${a[1]}
arr=( "${a[@]:2}" )

declare -p b c arr # print definitions of variables b, c, and arr

...properly emits:

declare -- b="1"
declare -- c="2"
declare -a arr='([0]="3" [1]="4" [2]="5" [3]="6")'

Upvotes: 4

Related Questions