Dolan
Dolan

Reputation: 41

Bash arrays: compound assignments fail

I have no idea why the compound array initialization does not work for me.

minimal example:

#!/bin/bash
#
MINRADIUS=( 'foo' 'bar' 'foobar' )
for i in {0..2..1}; do echo ${MINRADIUS[$i]}; done

output is

$ sh test.sh
(foo bar foobar)

with 2 additional blank lines.

Fieldwise initialization works:

#!/bin/bash
#
MINRADIUS[0]="foo"
MINRADIUS[1]="bar"
MINRADIUS[2]="foobar"
for i in {0..2..1}; do echo ${MINRADIUS[$i]}; done

$ sh test.sh
foo
bar
foobar

I have tried every possible combination of braces, quotes and "declare -a".

Could it be related to my bash version? I'm running version 4.1.2(1).

Upvotes: 0

Views: 960

Answers (3)

Go Dan
Go Dan

Reputation: 15502

I would suspect there is some quoting going on in your first example using compound assignments. Using this modified test script:

#!/bin/bash

echo "SHELL=${SHELL}"

echo 'Single-quoted v:'
v='(a b c)'; for i in {0..2}; do echo "v[$i]=${v[i]}"; done

echo 'Double-quoted v:'
v="(a b c)"; for i in {0..2}; do echo "v[$i]=${v[i]}"; done

echo 'Unquoted v:'
v=(a b c); for i in {0..2}; do echo "v[$i]=${v[i]}"; done

I get the following output:

$ sh test.sh
SHELL=/bin/bash
Single-quoted v:
v[0]=(a b c)
v[1]=
v[2]=
Double-quoted v:
v[0]=(a b c)
v[1]=
v[2]=
Unquoted v:
v[0]=a
v[1]=b
v[2]=c

If you quote the assignment, it becomes a simple variable assignment; a simple mistake to make that is easily overlooked.

Upvotes: 0

karolba
karolba

Reputation: 1020

The problem is, you are not using bash. Shebang doesn't matter if you run your script throught sh. Try bash instead.

Upvotes: 1

Vishal R
Vishal R

Reputation: 1074

I tried the below code and its working fine for me. Using bash 3.2.39(1)-release

#!/bin/bash
#
MINRADIUS=( 'foo' 'bar' 'foobar' )
for i in {0,1,2}; do echo ${MINRADIUS[$i]}; done

Output for this was

foo
bar
foobar

For me with your code it was giving an error

line 4: {0..1..2}: syntax error: operand expected (error token is "{0..1..2}")

Upvotes: 0

Related Questions