Bootstrap FreeKB - Bash (Scripting) - Convert string to list
Bash (Scripting) - Convert string to list

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter edb578 in the box below so that we can be sure you are a human.