Bash – Split string by space character

To split a string by single space character into an array of values in Bash scripting, you can set IFS (Internal Field Separator) variable with single space character, and then use read command with options ra to read the string as values to an array.

Once the values are into an array, we can access them using a For Loop.

Example

In the following script, we take a string in str which contains values separated by space. We split this string into values, and then print each of them to output.

example.sh

</>
Copy
#!/bin/bash
 
str="apple banana cherry mango"

# space character is set as delimiter
IFS=' '

# str is read into an array as tokens separated by IFS
read -ra values <<< "$str"

#echo each of the value to output
for value in "${values[@]}"; do
    echo "$value"
done

Output

sh-3.2# ./example.sh 
apple
banana
cherry
mango

References

Bash For Loop

Conclusion

In this Bash Tutorial, we learned how to split a string by single space.