How to find length of string in shell
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
Here are couple of ways to do it.
myvar="This is a test"
echo "${#myvar}"
14
Or
expr length "${myvar}"
14
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.