Bash – Iterate over characters in string

To iterate over characters in a string in Bash scripting, you can use a For loop statement with a counter. The counter runs from 0 upto length of the string, and during each iteration, we access the character in string using counter.

Reference Bash For Loop

Example

In the following script, we take a string in str, and iterate over the individual characters in the string using a for loop.

example.sh

#! /bin/bash
 
str="apple"
for ((i=0;i<${#str};i++)); do
    char=${str:i:1}
    echo $char
done

Output

sh-3.2# ./example.sh 
a
p
p
l
e
ADVERTISEMENT

Conclusion

In this Bash Tutorial, we learned how to iterate over the characters in a string using For loop statement.