Search code examples
stringbashifs

splitting a string into individual characters in bash using IFS


I'm trying to split a string into individual characters. For example temp="hello" into "h", "e", "l", "l", "o"

I tried using IFS because that's what I used in previous string splits and wanted to keep the consistency across the script. IFS='' read h e l l o <<<"$temp" does not work. What am I doing wrong?


Solution

  • You can use fold:

    arr=($(fold -w1 <<< "$temp"))
    

    Verify:

    declare -p arr
    declare -a arr='([0]="h" [1]="e" [2]="l" [3]="l" [4]="o")'