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

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.

#!/bin/bash
# Write a shell script to echo the length of the given string as argument.
string="$1"
 
if [ $# -eq 0 ]
then
        echo "Syntax: $(basename $0) string"
        exit 1
fi
 
# get length of the string
length=$(echo ${#string})
 
echo "String length = $length"

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

#!/bin/bash
# Write a shell script to echo the length of the given string as argument.
# Version 2, as suggested by  Chris F.A. Johnson
string="$@"
 
if [ $# -eq 0 ]
then
        echo "Syntax: ${0##*/} string"
        exit 1
fi
 
# get length of the string
length=${#string}
 
echo "String length = $length"
Get the latest tutorials on SysAdmin, Linux/Unix, Open Source, and DevOps topics:
Category List of Unix and Linux commands
File Management cat
Firewall Alpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilities dig host ip nmap
OpenVPN CentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Manager apk apt
Processes Management bg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searching grep whereis which
User Information groups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPN Alpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
5 comments… add one
  • Chris F.A. Johnson Jan 23, 2010 @ 0:25

    bullygram, your script is functionally equivalent to:

    clear
    read -ep $’enter the string\n’ str
    printf “length\n%d\n” ${#str}

  • bullygram Oct 2, 2009 @ 20:47

    we can also do like this!

    program:
    #!/bin/bash
    #include
    clear
    echo “enter the string”
    read str
    for i in “$str”;do
    echo “length”
    echo ${#i}
    done

  • vivek Aug 9, 2008 @ 9:59

    Thanks for sharing tips.

  • Chris F.A. Johnson Aug 7, 2008 @ 19:42

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

    length=${#string}

    • Suresh Feb 3, 2011 @ 13:44

      Hi Chris,

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

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

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

      Regards,
      Suresh

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.