1

How should I loop through all chars in a string.

My pseudocode

stringVar="abcde"

for var in stringvar
{
   do some things with var
}

result i need
a

b

c

d

I want to loop all the vars but i can only get it to work with a whitespace splitted var like

 stringVar="a b c"


for var in stringVar; do
   echo $var
done;

result

a

b

c

but i cant do it for a string that isnt split with whitespaces.

The question is flagged as duplicate but not one of the answers (with upvotes) is available in the linked questions..

Cœur
  • 32,421
  • 21
  • 173
  • 232
Sven van den Boogaart
  • 10,022
  • 13
  • 76
  • 138

2 Answers2

7

You can use read for that:

string="abcde"
while read -n 1 char ; do
    echo "$char"
done <<< "$string"

Using -n 1 read will read one character at a time. However, the input redirection <<< adds a newline to the end of $string.

hek2mgl
  • 133,888
  • 21
  • 210
  • 235
  • this method skips white spaces, unfortunately – almaceleste Dec 13 '20 at 15:01
  • can't reproduce – hek2mgl Dec 14 '20 at 09:33
  • you used `echo` which creates a new line on each iteration. if you try with `printf` you'll see that this method skips spaces. here is an [example](https://repl.it/@almaceleste/loop-chars#main.sh) – almaceleste Dec 14 '20 at 10:45
  • ok, you have to use `IFS= read -n 1 char` to read spaces too. example: [read-spaces](https://repl.it/@almaceleste/read-spaces#main.sh) – almaceleste Dec 14 '20 at 11:12
  • @almaceleste https://pastebin.com/BTZ7BNjB – hek2mgl Dec 14 '20 at 11:33
  • @hek2ml, your example does not work with spaces - it skips them. to test this behavior simply change `echo "@char"` to `printf "@char"` or use `echo` with some mark in the beginning and ending of the printed string, for example `'` (single quote) - like `echo "'$char'"`. [here](https://repl.it/@almaceleste/loop-chars-2#main.sh) is your code with single quotes appended to the `echo` command. if you want the command `read -n 1 char` to read spaces, you need to prepend it with `IFS=` or `IFS=""` or `IFS=''` like in this [example](https://repl.it/@almaceleste/loop-chars-3#main.sh) – almaceleste Dec 14 '20 at 14:31
  • 1
    Now I understand what you mean. – hek2mgl Dec 14 '20 at 14:40
  • ps: will review my answer later, at work atm.. thank you! – hek2mgl Dec 14 '20 at 15:59
3
stringVar="abcde"
for ((i=1;i<=${#stringVar};i++)); do
  echo ${stringVar:$i-1:1}
done

Output:

a
b
c
d
e
Cyrus
  • 69,405
  • 13
  • 65
  • 117