0

How can ı convert a string to an array in shell script?

For example i want to put "apple" to an array.

array[0] = a
array[1]=p
array[2]=p
array[3]=l
array[4]=e

I tried a lot of things but none of them worked. I tried to use IFS but i have no space or comma in my word so it didn't work.

James Z
  • 12,209
  • 10
  • 24
  • 44
lolndrug
  • 1
  • 2
  • Umm. Is your expected result `array[0]="apple"`?, or is your expected result `array=( [0]=a [1]=p [2]=p [3]=l [4]=e )`? Don't just show what you're doing, show how you're testing whether it worked, and show the output you _want_ that test to have. – Charles Duffy Nov 02 '22 at 16:43
  • (Or if you're _only_ showing the output you want, also describe how you're trying to accomplish it! We generally don't do "write your program for you" here; we answer questions, ideally ones about narrow, specific problems that can be demonstrated via code you already wrote, which means we expect you to _show your existing code_) – Charles Duffy Nov 02 '22 at 16:46
  • Bro chill out. This is the first time I have asked something on StackOverflow. So you don't have to be so offensive. I just started to learn shell script plus I don't need you to write my code. I don't know the language so well, so I asked about it. – lolndrug Nov 03 '22 at 17:13
  • What's offensive? Since you're new here, there's a lot of guidance on how best to navigate the site to be learned-- it's a lot shorter (and more helpful) for advice on how to comply with the site's rules to be compressed in a few short sentences, like the above, than to ask you to read the whole [Help Center](https://stackoverflow.com/help) front-to-back. – Charles Duffy Nov 03 '22 at 18:04

1 Answers1

0

Parameter expansion is relevant here: ${#var} gives you the number of characters in var, and ${var:start:len} takes len characters from var, starting at position start.

Combine those two techniques and you get:

#!/usr/bin/env bash
string='apple'
array=( )
for ((i=0; i<${#string}; i++)); do
  array[$i]=${string:i:1}
done
declare -p array

...which emits as output:

declare -a array=([0]="a" [1]="p" [2]="p" [3]="l" [4]="e")
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441