Shell script to echo the length of the given string as argument

in Categories Academic, String Management last updated August 9, 2008

Length is the long dimension of any object. The length of a thing is the distance between its ends, its linear extent as measured from end to end. This shell script will find out given string length as command line argument.

Following script optimized for speed, as suggested by Chris (see below in comments section)

Share this on:

5 comment

  1. we can also do like this!

    echo “enter the string”
    read str
    for i in “$str”;do
    echo “length”
    echo ${#i}

  2. echo “Syntax: $(basename $0) string”

    Why use an external command? The shell can do it internally:

    echo “Syntax: ${0##*/} string”

    length=$(echo ${#string})

    What’s the point of using echo and command substitution (which is slow)?


    1. Hi Chris,

      When I embed this “length=${#string}” in bash shell script it was throwing an error as shown below
      “ bad substitution”

      I guess, shell interpretted string after “#” character as comment.

      Please help me out escape the # character and get required result.


    Have a question? Post it on our forum!