help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Taking a slice of an array


From: Greg Wooledge
Subject: Re: [Help-bash] Taking a slice of an array
Date: Mon, 9 Apr 2012 09:22:05 -0400
User-agent: Mutt/1.4.2.3i

On Sun, Apr 08, 2012 at 08:59:46PM -0600, Bill Gradwohl wrote:
> #!/bin/bash
> array=(a b c d e f g)
> echo "${array[1]} ${#array[1]}"
> string="address@hidden:1:4}"

At this point, you're doing something odd.  You're using "$@" syntax
(which results in multiple words), but you're doing it on the right-hand
side of an assignment, which means you're forcing there to be just one
word.  The two are fundamentally incompatible, and in this case, the
assignment (forcing one word) wins.

> I was expecting 'bcde' with a length of 4 after reading man bash.
> Why the spaces?

If you're trying to generate a single string composed of several array
elements, then you want to use the "$*" syntax with an empty IFS.

imadev:~$ array=(0 1 2 3 4 5 6 7 8 9); IFS=; string="${array[*]:1:4}"; unset 
IFS; echo "<$string>"
<1234>

> I thought that possibly it was some IFS related issue so I set IFS='' on a
> separate statement but that changed nothing.

IFS is only used by the "$*" notation, not by the "$@" notation.

imadev:~$ array=(0 1 2 3 4 5 6 7 8 9); IFS=; string="address@hidden:1:4}"; 
unset IFS; echo "<$string>"
<1 2 3 4>
imadev:~$ array=(0 1 2 3 4 5 6 7 8 9); IFS=x; string="address@hidden:1:4}"; 
unset IFS; echo "<$string>"
<1 2 3 4>

IFS is ignored completely by "$@".  Since you're doing this weird "mutliple
words, no wait, just one word" thing, bash decides to give you one word
with spaces in it.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]