Feed on
Posts
Comments

to get the length of a string in the bash shell:

${#str_var}


Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

7 Responses to “get length of a string in bash shell”

  1. on 31 Oct 2008 at 2:44 pm Alexander

    Great! The web is full of crappy complicated methods for getting the string length. This is the most simple and elegant one.

  2. on 02 Aug 2009 at 10:10 pm volpe

    I quote Alexander. Thank you!

  3. on 14 Oct 2010 at 9:44 am DAud_IcI

    Wow, this is awesome, thank you! Very elegant.

  4. on 23 Apr 2011 at 8:25 am Droidzone

    Thanks a lot..It helped

  5. on 25 Jun 2011 at 11:24 am GMorris

    Well, I have all the latest updates to BASH and all, and just upgraded my system a couple of months ago, so I know it can’t be a “backwards compatibility” problem. I tried this, and it returns:

    bash: 11: command not found…

    The “11″ IS the length of the string, and I tried it with different lengths which all are correct. I just don’t get where the alleged “error” is originating. Any ideas?

  6. on 25 Jun 2011 at 11:37 am GMorris

    Ahh, OK, I’ve figured this out. It works a lot better if you DO something with it, like “echo ${#str_var}”. I had used ‘expr length “$str_var”‘, so I was thinking along those lines as it returns the length without an ‘echo’. Duhh… I guess just because the ‘echo’ wasn’t in the post I assumed it would work the same way, but you know what they say about ‘ass u me’?

    Now I’ve succeeded in becoming a true idiot, and I feel like it too!

  7. on 10 Jul 2011 at 11:24 am mark

    thanks for this, simple and works.

    I saw so many posts that were doing

    echo $var | wc -c

    but the method you posted is a lot more simpler

Did I get this wrong? Let me know!

Trackback URI | Comments RSS