Bash (Scripting) - Convert string to list

by
Jeremy Canfield |
Updated: August 25 2024
| Bash (Scripting) articles
In this example, the "greeting" variable contains string "Hello World" and "list" is an array that contains two elements, Hello and World.
#!/bin/bash
greeting="Hello World"
declare -p greeting
list=($greeting)
declare -p list
Or like this.
#!/bin/bash
greeting="Hello World"
declare -p greeting
declare -a "list=($greeting)"
declare -p list
Running this script should return the following. The two dashes (--) means that "greeting" is a variable and -a means that "list" is an array.
$ bash demo.sh
declare -- greeting="Hello World"
declare -a list=([0]="Hello" [1]="World")
By default, the elements in a string will be delimited using whitespace since the Internal Field Separator (IFS) by default splits at whitespace. In this example, a comma is set as the delimiter.
#!/bin/bash
IFS=$','
greeting="Hello,World"
declare -p greeting
declare -a "list=($greeting)"
declare -p list
Running this script should return the following.
]$ bash ~/adsfafkldadjsfl.sh
declare -- greeting="Hello,World"
declare -a list=([0]="Hello" [1]="World")
Did you find this article helpful?
If so, consider buying me a coffee over at