Bash Script to Count Characters in a String
Use
echo -n "$string" | wc -m in Bash to count the number of characters in a string, where $string is your input.Examples
Inputhello
Output5
InputBash scripting!
Output15
Input
Output0
How to Think About It
To count characters in a string, think of the string as a sequence of letters and symbols. You want to find how many characters it has by sending it to a tool that counts characters, ignoring any extra new lines or spaces.
Algorithm
1
Get the input string.2
Send the string to a command that counts characters without adding extra new lines.3
Output the count as the result.Code
bash
#!/bin/bash string="Hello, world!" count=$(echo -n "$string" | wc -m) echo "$count"
Output
13
Dry Run
Let's trace the string "Hello, world!" through the code
1
Set string variable
string="Hello, world!"
2
Count characters
echo -n "Hello, world!" | wc -m # outputs 13
3
Print count
echo "13"
| Step | Operation | Value |
|---|---|---|
| 1 | string variable | Hello, world! |
| 2 | character count | 13 |
| 3 | output | 13 |
Why This Works
Step 1: Use echo -n
The -n option with echo prints the string without adding a new line, so the count is accurate.
Step 2: Pipe to wc -m
The wc -m command counts the number of characters from the input it receives.
Step 3: Store and print
We save the count in a variable and then print it to show the result.
Alternative Approaches
Using parameter expansion
bash
#!/bin/bash string="Hello, world!" count=${#string} echo "$count"
This method is faster and simpler because it uses Bash's built-in string length feature without calling external commands.
Using printf and wc
bash
#!/bin/bash string="Hello, world!" count=$(printf "%s" "$string" | wc -m) echo "$count"
Using <code>printf</code> avoids issues with echo variations and is more portable.
Complexity: O(n) time, O(1) space
Time Complexity
Counting characters requires looking at each character once, so it takes linear time proportional to the string length.
Space Complexity
The operation uses constant extra space since it only stores the count and the input string.
Which Approach is Fastest?
Using Bash's built-in ${#string} is fastest because it avoids spawning external commands like echo and wc.
| Approach | Time | Space | Best For |
|---|---|---|---|
| echo + wc -m | O(n) | O(1) | Simple scripts, portability |
| Bash ${#string} | O(n) | O(1) | Fastest, pure Bash |
| printf + wc -m | O(n) | O(1) | Portable and reliable output |
Use Bash's built-in
${#string} to count characters efficiently without external commands.Forgetting
-n with echo adds a newline, causing the count to be off by one.