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:
- Shell Script To Concatenate Two String Given as Input including its length
- Shell Script To Check String Length (Display Message If It Doent't Have At Least 5 Characters )
- Shell script to read a character (upper or lower), digit, special symbol and display message according to the character entered
- Shell script to read 5 digit number and calculate the sum of digit
- Shell Script to read the base and height of a traingle and find its area
Discussion on This Shell Script:
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!
Tags: argument string, command line argument, eq, fi, if command, shell script, string length ~ Last updated on: August 9, 2008


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}
Thanks for sharing tips.