Shell scripting tip: Find the length of a string under UNIX / Linux oses
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:
expr length STRING
For example display the length of "nixcraft" word:
expr length "nixcraft"
Output:
8
expr and POSIX
However expr command is not concerned with POSIX (open system standards based on Unix). You can try old good KSH/Bash command (also following command should work with other UNIX like oses such as FreeBSD / Solaris ):
myVar="nixcraft"
echo ${#myVar}
Output:
8
Want to stay up to date with the latest Linux tips, news and announcements? Subscribe to our free e-mail newsletter or RSS feed to get all updates.
You can Email this page to a friend.
You may also be interested in other helpful articles:
- Capturing or cutting few characters of a string
- Find out if file exists with conditional expressions
- Compressing large Apache log files on a shared hosting server
- Finding all .mp3 files and move to new directory from shell prompt
- How do I replace text string in many files at once?
Discussion on This Article:
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: bash, bsd, expr_command, gnu, ksh, length in unix, length of a string in unix, length unix, length_of_string, linux script length of string, linux shell, linux shell script string length, open_system_standards, posix, shell string length, shell_script, size of output string, string length shell, unix script string length



Few more examples:
% echo nixcraft | awk ‘ { print length } ‘
8
% echo nixcraft | perl -nle ‘ print length ‘
Corey,
Nice awk / perl tips
Appreciate your post!