While writing a shell script you may want to find out the length of a string. While reading GNU expr command man page I found an interesting option as follows:
expr length STRING
For example display the length of "nixcraft" word/string, enter:
expr length "nixcraft"
OR set it as follows:
var="nixcraft" expr "${var}" : '.*'
Sample outputs:
8
Finding length of string in bash
The syntax is as follows:
var="nixCraft" l=${#var} echo "Length of string \"${var}\" is ${l}."
Sample outputs:
Length of string "nixCraft" is 8.
String length in ksh or older unix oses
You can use the wc command as follows:
## pass the -c option to wc to get the number of bytes in $domain variable ## domain='www.cyberciti.biz' echo -n "$domain" | wc -c
Sample outputs:
17
expr and POSIX
Please note that the expr command is not concerned with POSIX (open system standards based on Unix). You can try old good KSH/SH/Bash command as follows which should work with any UNIX-likeo operating systems such as FreeBSD, OpenBSD, Solaris, IBM AIX, HP-UX and more:
myVar="nixcraft" echo "${#myVar}"
Sample outputs:
8
Another option is to use Perl or Python:
echo "What you seek is seeking you" | perl -nle ' print length '
Sample outputs:
28
Few more examples:
% echo nixcraft | awk ' { print length } '
8