Array and field separator

Hi all,

I have an array in BASH and I need to change the IFS in order to split up it correctly.
Here an example:

array_test=(hello world+sunny)

for elem in ${array_test[@]}; do
  echo $elem
done

echo -e "\n changed IFS \n"
OLD_IFS=$IFS
IFS=+

for elem in ${array_test[@]}; do
  echo $elem
done

here the output:

hello
world+sunny

 changed IFS

hello
world
sunny

The first 2 lines are printed correctly but after the modification of IFS I was expecting a different output according to the new + separator like:

hello world
sunny

Am I missing something?

thanks in advance

IFS=+
for elem in `echo "${array_test[@]}"`; do
   echo $elem
done
hello world
sunny

Hi
Thanks for reply, I figure out also another way:
just add double quote to the array

array_test=("hello world+sunny")

hello world
sunny

The shell field/word splitting occurs only on expansion.

From the manual pages of bash:

So:

4.1.10(4)-release$ IFS=+
4.1.10(4)-release$ a=( one+two )
4.1.10(4)-release$ echo "${a[0]}"
one+two

Use some kind of expansion:

4.1.10(4)-release$ s='one+two'
4.1.10(4)-release$ a=( $s )
4.1.10(4)-release$ echo "${a[0]}"
one

Consider the following:

elements='hello world+sunny'

# $elements is not quoted so it is
# subject to word splitting
# based on the current value
# of IFS

array_test=( $elements )

for elem in "${array_test[@]}"; do
  printf '%s\n' "$elem"
done

printf '\nChanging IFS to %s\n\n' +

IFS=+

# we need to reassign 
# in order to perform word
# splitting based on the 
# new IFS value

array_test=( $elements )

for elem in "${array_test[@]}"; do
  printf '%s\n' "$elem"
done

This is the output:

4.1.10(4)-release$ ./s
hello
world+sunny

Changing IFS to +

hello world
sunny

With recent versions of bash you could use something like this too:

4.1.10(4)-release$ IFS=+ read -ra arr <<<'one+two'
4.1.10(4)-release$ printf '%s\n' "${arr[0]}"
one
1 Like