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:
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: