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
  • 363,520
  • 117
  • 767
  • 871
Jack Slater
  • 143
  • 6

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
  • 150,973
  • 38
  • 327
  • 406
Sebastian
  • 8,677
  • 4
  • 39
  • 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](http://unix.stackexchange.com/questions/87745/what-does-lc-all-c-do) – 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
  • 4