How to split a string in Bash

Splitting a string in bash is easy with the help of the internal field separator (IFS).

Bash string split using IFS

1
2
3
4
5
6
string="you got a friend in me"
IFS=' ' read -ra split <<< "$string"
echo "${split[*]}"
# Output: you got a friend in me
echo "${split[3]}"
# Output: friend

The above method does not interfere with the IFS global variable since it’s only set for that single invocation.