Bash – Print unique characters in string

To print unique characters in a string in Bash scripting, iterate over the characters in given string and store them in an associate array where keys of this array are the unique characters in the given string.

Example

In the following script, we take a string in str. We get the unique characters of the string into an associative array and print them to output using echo.

example.sh

#!/bin/bash
 
string="helloworld"
declare -A char_count

for ((i=0; i<${#string}; i++)); do
  char=${string:i:1}
  char_count["$char"]=1
done

for char in "${!char_count[@]}"; do
  echo "$char"
done

Output

# bash example.sh 
w
r
o
l
h
e
d

References

Bash For Loop

ADVERTISEMENT

Conclusion

In this Bash Tutorial, we learned how to print the unique characters in given string using associative arrays and For loop.