linux poison RSS
linux poison Email

Bash Script: Get the length of any given String

Below is a simple script to get the length of any string.

#!/bin/bash
echo "enter the sting: "
read str;

countStringLength() {
        echo `echo -n $1 | wc -c`

        # Or can use the below trick to get the string length
        # I prefer to use the first one - easy to use and easy to remember
        echo ${#1}
}
countStringLength $str




1 comments:

Abdul Khader said...

1) echo `echo -n $1 | wc -c`
============================
The above option will not be able to calculate properly length if there are more than 1 spaces in the string.
Example:
a="1234567890 0987654321"
b="1234567890 0987654321"
echo `echo -n $a | wc -c`
echo `echo -n $b | wc -c`


2) echo ${#1}
=============
This above option will be able to count the length even if there are multiple space in the string. See the below for example.

vi length.sh
a="1234567890"
b="1234567890 0987654321"#Here there is only once space in between.
c="1234567890 0987654321"#Here there are 2 spaces in between

echo ${#a}
echo ${#b}
echo ${#c}

chmod +x length.sh
./length.sh

Post a Comment

Related Posts with Thumbnails