Bash Script to Count Words in a String
Use
echo "$string" | wc -w in Bash to count the number of words in a string.Examples
Inputhello world
Output2
Input this is a test string
Output5
Input
Output0
How to Think About It
To count words in a string, think of splitting the string by spaces and counting each piece. The
wc -w command counts words from input, so we send the string to it using echo and a pipe.Algorithm
1
Get the input string.2
Send the string to the word count command using a pipe.3
Count the words and return the result.Code
bash
#!/bin/bash string="$1" word_count=$(echo "$string" | wc -w) echo "$word_count"
Output
2
Dry Run
Let's trace the string 'hello world' through the code
1
Assign input string
string='hello world'
2
Count words
echo 'hello world' | wc -w outputs 2
3
Print result
echo 2
| Step | Action | Value |
|---|---|---|
| 1 | string variable | hello world |
| 2 | word count command output | 2 |
| 3 | final output | 2 |
Why This Works
Step 1: Use echo to output the string
The echo command prints the string so it can be processed by other commands.
Step 2: Pipe output to wc -w
The pipe | sends the string to wc -w, which counts the words.
Step 3: Store and print the count
The word count is saved in a variable and printed to show the result.
Alternative Approaches
Using set and $#
bash
#!/bin/bash
string="$1"
set -- $string
echo $#This splits the string into positional parameters and counts them with <code>$#</code>. It is fast but changes shell parameters.
Using array and length
bash
#!/bin/bash string="$1" read -ra words <<< "$string" echo "${#words[@]}"
This reads words into an array and counts elements. It is clean and safe for scripts.
Complexity: O(n) time, O(n) space
Time Complexity
The script processes each character once to split words, so time grows linearly with string length.
Space Complexity
Extra space is used to hold the string and split words temporarily, proportional to input size.
Which Approach is Fastest?
Using set -- $string is fastest but modifies shell state; wc -w is simple and safe; arrays offer clarity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| echo + wc -w | O(n) | O(n) | Simple and safe word count |
| set and $# (positional params) | O(n) | O(n) | Fast but changes shell parameters |
| array and length | O(n) | O(n) | Clear and safe in scripts |
Always quote your string variable like "$string" to preserve spaces correctly.
Not quoting the string can cause word splitting errors or wrong counts.