0

I am accepting input from a user by using read. I am trying to count the result as usual with wc -c, and store it into a variable, but the result always returns 1.

Below is the

#!/bin/bash 

echo -n "Enter your plaintext.> "
read text

count=$(echo $text | wc -w)
echo  $count

Somehow when the variable is not store as variable and directly echo out will be the correct result.

#!/bin/bash 

echo -n "Enter your plaintext.> "
read text

echo $text | wc -w

closed as off-topic by Jeff Schaller, roaima, Satō Katsura, GAD3R, thrig Feb 6 '17 at 16:33

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions describing a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers." – Jeff Schaller, roaima, Satō Katsura, GAD3R
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    Welcome to Unix Stackexchange! You can take the tour first and the learn How to Ask a good question. That makes it easier for us to help you. – andcoz Feb 6 '17 at 13:27
  • I tried the code in the question and It worked for me. – andcoz Feb 6 '17 at 13:30
  • @andcoz it is correct if you counting the word ,but I specify a -c to count the character which isn't correct – Leon Armstrong Feb 6 '17 at 13:33
  • 1
    In question text you talk of wc -c while in the code you use wc -w, which one is the correct one? What are you triyng to count? Words or characters? – andcoz Feb 6 '17 at 13:38
  • Guess i got a typo error myself... – Leon Armstrong Feb 6 '17 at 13:41
3

Your code works.

read text
count=$( echo "$text" | wc -w )

This will set count to 2 if I enter the text hello world.

In the comments, you talk about counting characters.

count=$( echo "$text" | wc -c )

or

count=${#text}

will do that for you. However, the wc solution will also count the final newline, giving you a value that is one character larger than the parameter expansion method. The wc method will also compress spaces in the string unless you double quote the expansion of $text like I've done above.

  • Thanks for an clear answer although it is just a typo , but I expect more downvote to make this question less relevant to search in this community. – Leon Armstrong Feb 6 '17 at 15:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.