HowTo: Bash Shell Split String Into Array

ww‮ttual.w‬uri.com
HowTo: Bash Shell Split String Into Array

To split a string into an array in Bash shell, you can use the read command and the -a option.

The read command allows you to read a string and split it into fields, and the -a option allows you to specify an array in which to store the fields.

Here is an example of how you can use the read command and the -a option to split a string into an array:

# Define the string
string="one two three four"

# Split the string into an array
read -a array <<< "$string"

# Print the array elements
echo "Array element 1: ${array[0]}"
echo "Array element 2: ${array[1]}"
echo "Array element 3: ${array[2]}"
echo "Array element 4: ${array[3]}"

This will split the string "one two three four" into an array with four elements, and print the array elements. The output will be:

Array element 1: one
Array element 2: two
Array element 3: three
Array element 4: four

You can also use the IFS variable to specify the delimiter used to split the string. For example, to split the string using a comma as the delimiter, you can use the following command:

# Set the IFS variable to a comma
IFS=','

# Split the string into an array
read -a array <<< "$string"

This will split the string "one,two,three,four" into an array with four elements.

Overall, the read command and the -a option are useful tools for splitting a string into an array in Bash shell. They allow you to easily split a string into fields and store the fields in an array, and customize the delimiter used to split the string.

Created Time:2017-10-29 22:08:42  Author:lautturi