Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash loop through all chars in string [duplicate]

Tags:

bash

shell

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..

like image 985
Sven van den Boogaart Avatar asked Dec 08 '25 06:12

Sven van den Boogaart


2 Answers

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.

like image 190
hek2mgl Avatar answered Dec 10 '25 20:12

hek2mgl


stringVar="abcde"
for ((i=1;i<=${#stringVar};i++)); do
  echo ${stringVar:$i-1:1}
done

Output:

a
b
c
d
e
like image 41
Cyrus Avatar answered Dec 10 '25 22:12

Cyrus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!