nixCraft Poll

Topics

Shell scripting tip: Find the length of a string under UNIX / Linux oses

Posted by Vivek Gite [Last updated: June 19, 2008]

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:

Discussion on This Article:

  1. Corey Hart Says:

    Few more examples:

    % echo nixcraft | awk ‘ { print length } ‘
    8

    % echo nixcraft | perl -nle ‘ print length ‘

  2. vivek Says:

    Corey,

    Nice awk / perl tips :)

    Appreciate your post!

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!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Tags: , , , , , , , , , , , , , , , , , ,

Copyright © 2004-2008 nixCraft. All rights reserved - TOS/Disclaimer - Privacy policy - Sitemap - Powered by Open source software.