How to find length of string in shell

I need to calculate the length of a string using pure sh shell only. What is happening is that /bin/sh is actually a soft link to bash or another shell. Hence ${#STRING} gives the length of string as it is advance bash feature.

Can someone tell me how I can find length of string? I am using Solaris 5.10 Sparc architecture


Solution 1:

wc -m counts the chars in a string. So you can do something like:

STRLENGTH=$(echo -n $STRING | wc -m)

Alternative syntax:

STRLENGTH=`echo -n $STRING | wc -m`

The -n flag for echo stops it from printing a newline. The flag might be different on Solaris 5. Check man echo

Solution 2:

Here are couple of ways to do it.

myvar="This is a test"
echo "${#myvar}"
14

Or

expr length "${myvar}"
14

Solution 3:

Using ${#string} to get the length of $string is a POSIX shell parameter expansion. It is not a bash-only feature.

On Solaris 5.10, if /bin/sh or /usr/bin/sh (as mentioned in the sh(1) manual) does not support this, then /usr/xpg4/bin/sh will.

To get POSIX behaviour on a Solaris 5.10 system, your PATH should be set to

/usr/xpg6/bin:/usr/xpg4/bin:/usr/ccs/bin:/usr/bin

(in that order), as described in the standards(5) manual.