11

I'm trying to learn the basics and I have run into an issue with my script counting the characters of a user's input. Here is my script, can someone point out where I'm going wrong please?

#!/bin/bash

echo "Enter a word!"    
read INPUT_STRING   
len= echo $INPUT_STRING | wc -c 
echo "Your character length is " $len
exit
slm
  • 369,824

2 Answers2

13

every beginning is hard:

#!/bin/bash
read INPUT
echo $INPUT
len=$(echo -n "$INPUT" | LC_ALL=C.UTF-8 wc -m)
echo $len

specifically, there must not be a space surrounding = and a separate command needs to be enclosed inside $(...). Also, you might want to write your variables in quotes " using this syntax "${INPUT}", this ensures that the variable is not accidentally concatenated with what follows and can contain special chars (e.g. newlines \n).

cuonglm
  • 153,898
Sebastian
  • 8,817
  • 4
  • 40
  • 49
  • sorry for future reference could you tell me what the -n does and LC_ALL=C.UTF-8 because I would like to know of its purpose. Thank you – Jack Slater Sep 19 '14 at 08:19
  • 1
    to find the meaning of a command line switch, try using the man command (in this case man echo: -n do not output trailing newline). Frequent invocation of man will advance your linux skills rapidly. For more info on LC_ALL, see this question/answer – Sebastian Sep 19 '14 at 08:34
  • 1
    copy from link: You generally run a command with LC_ALL=C to avoid the user's settings to interfere with your script. For instance, if you want [a-z] to match the 26 ASCII characters from a to z, you have to set LC_ALL=C – Sebastian Sep 19 '14 at 08:43
8

I think preferably would be to use

len=${#INPUT_STRING}

as otherwise the end of line character added by echo will be counted in as well. Unless that is what you want.

bfloriang
  • 193