How to count the number of words in a string in Bash

bash, linux, shell

Solution

You can use `wc`:

$ wc -w <<< "$str"
3

Problem

I have the following string which contains words separated by spaces ``` str="word1 word2 word3" ``` How to count the number of words? I do not want to use a for loop with counter. I want to do it in one command.

Original source

Related problems