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
12

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).

  • 1
    Thank you my code works now, and the additional help shall help me in the future. Thanks – Jack Slater Sep 18 '14 at 12:47
  • @Gnouc Thank you for this insightful edit! still learning... – Sebastian Sep 18 '14 at 13:07
  • 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 8: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 8: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 8: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.

  • I agree, it's shorter and faster. – Franki Sep 18 '14 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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