About

Script Categories

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

Posted in Academic » String Management

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"

Download - Email this to a friend - Printable version

Is your site working? Monitor Your Web Site 24/7. Get SMS alerts on server downtime! Free 30-day trial including 20 SMS!

Related Other Helpful Shell Scripts:

Discussion on This Shell Script:

  1. Chris F.A. Johnson Says:

    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}

  2. vivek Says:

    Thanks for sharing tips.

Leave a Reply

We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Tags: , , , , , , ~ Last updated on: August 9, 2008