Parsing delimited strings into an array in Bash - why is "$ var" different from $ var, although there are no spaces in the $ var variable?

I am running Bash version 4.2.25. Here is my code:

#!/usr/bin/env bash

string="one:two:three:four"

# without quotes
IFS=: read -ra array_1 <<< $string
for i in "${array_1[@]}"; do printf "i = [$i]\n"; done
# output:
# i = [one two three four]

# with quotes
IFS=: read -ra array_2 <<< "$string"
for i in "${array_2[@]}"; do printf "i = [$i]\n"; done
# output:
# i = [one]
# i = [two]
# i = [three]
# i = [four]

What explains the difference in behavior?

+4
source share
2 answers

I cannot reproduce your problem on Linux using bash 4.2.46 and bash 4.3.30. However, here is an adapted version that shows the described behavior:

string="one:two:three:four"
IFS=:

read -ra array_1 <<< $string
for i in "${array_1[@]}"; do printf "i = [$i]\n"; done
# i = [one two three four]

read -ra array_2 <<< "$string"
for i in "${array_2[@]}"; do printf "i = [$i]\n"; done
# i = [one]
# i = [two]
# i = [three]
# i = [four]

This is because the variables are not actually divided into spaces, they are divided into $IFS(by default, this is a space, tab and line).

Since we redefined $IFSthis value with colons, we must be careful when quoting. Spaces no longer matter.

, bash hardcodes string_list, write_here_string. IFS , , , read , .

PS: , , , .

+3

. CHANGES , cygwin bash 4.3.48 (8) ( ). -, , repo redir.c, , .

+1

Source: https://habr.com/ru/post/1666423/


All Articles