We can use an internal field separator (IFS) variable to parse an array. Let’s use an example script, where first we define a string with colon-separated. Then we will use IFS to separate values based on a delimiter.
1 2 3 4 5 6 7 8 9 | #!/usr/bin/env bash STR="orange:grapes:banana:apple" #String with names IFS=';' read -ra NAMES <<< "$STR" #Convert string to array #Print all names from array for i in "${NAMES[@]}"; do echo $i done |
Advertisement
Let’s execute this script and check for results.
./myscript.sh
Output:orange grapes banana apple
2 Comments
Uugh, nothing works for me.
$ IFS=’;’ read -ra NAMES <<< "$STR"
syntax error: `<' unexpected
Its working for me thanks for the post