Convert a delimited string into an array in Bash

If you’ve got a string of items in bash which are delimited by a common character (comma, space, tab, etc) you can split that into an array quite easily. Simply (re)define the IFS variable to the delimiter character and assign the values to a new variable using the array=($<string_var>) syntax. The new variable will now be an array of strings as split by the delimiter character.

Let’s look at an example which converts the animal string, delimited by the “|” string, into an array before printing them all out. Notice that IFS is saved in OIFS at the start and restored at the end, just in case another script was using that variable too. Not necessary, but it’s good practice.

#!/bin/bash

OIFS=$IFS;
IFS="|";

animals="dog|cat|fish|squirrel|bird|shark";
animalArray=($animals);

for ((i=0; i<${#animalArray[@]}; ++i)); do     echo "animal $i: ${animalArray[$i]}"; done

IFS=$OIFS;

This will print:

animal 0: dog
animal 1: cat
animal 2: fish
animal 3: squirrel
animal 4: bird
animal 5: shark

Leave a Reply

Your email address will not be published. Required fields are marked *