Jes Jes - 3 months ago 9
Bash Question

Shell script split a string by space

The bash shell script can split a given string by space into a 1D array.

str="a b c d e"
arr=($str)

# arr[0] is a, arr[1] is b, etc. arr is now an array, but what is the magic behind?


But, what exactly happened when we can
arr=($str)
? My understanding is the parenthesis here creates a subshell, but what happen after that?

Answer

In an assignment, the parentheses simply indicate that an array is being created; this is independent of the use of parentheses as a compound command.

This isn't the recommended way to split a string, though. Suppose you have the string

str="a * b"
arr=($str)

When $str is expanded, the value undergoes both word-splitting (which is what allows the array to have multiple elements) and pathname expansion. Your array will now have a as its first element, b as its last element, but one or more elements in between, depending on how many files in the current working directly * matches. A better solution is to use the read command.

read -ar arr <<< "$str"

Now the read command itself splits the value of $str without also applying pathname expansion to the result.

Comments