Bash/KSH/SH Shell: Find The Length Of a String On a UNIX, Linux, BSD, and OS X

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:

ADVERTISEMENTS

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
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source & DevOps topics via:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
23 comments… add one
  • Corey Hart Aug 29, 2007 @ 20:02

    Few more examples:

    % echo nixcraft | awk ' { print length } '

    8

    % echo nixcraft | perl -nle ' print length '
  • 🐧 nixCraft Aug 29, 2007 @ 20:09

    Corey,

    Nice awk / perl tips 🙂

    Appreciate your post!

  • name Dec 17, 2008 @ 18:50

    echo -n “hello world” | wc -c

  • crazysenses Apr 29, 2009 @ 13:55

    Thanks for the tips
    It was very useful for my work
    Greetings from Mexico

  • hw May 10, 2009 @ 20:38

    hi i tried this program but its not working in my computer lab.
    kindly let me know what is wrong in the program
    echo enter the string
    read string
    length = ‘expr length $string’
    echo “length of the string is $length”

    output should come as
    eg:
    enter the string:Harshi
    length of the string is :6
    but in the lab its coming as
    enter the string :Harshi
    length command cannot be read
    please try to solve my problem
    thank you

    • Sola Jul 21, 2010 @ 9:09

      to hw,

      the correct code is:
      echo enter the string
      read string
      length=$(expr length “$string”)
      echo “length of the string is $length”

      You must redirect the output into the variable, otherwise it don’t read the value.
      Nice job.

    • sur Mar 15, 2011 @ 6:33

      i dunno y it is not working .have u given the inverted commas and stuffs??
      this code worked for me..

      echo ” enter thestring”
      read str
      len=`expr length $str`
      echo “Length is $len”.

  • seerum Jun 25, 2009 @ 10:10

    use length=`expr length $string` it will work

  • Will Jul 3, 2009 @ 0:49

    I am trying to create a string that will allow me to set value a a particular position in the string.
    I am running a validation an have many for loops with various variable lengths being returned.
    I want the output to be formatted so that the status is lined up in the same postion.
    for example i check a list of files to see if they exist and I want to display an OK or FAILED in the output. I want the output to look like something below.
    /IDS

  • Will Jul 3, 2009 @ 0:52

    sorry I didnt finish what I wanted to explain.
    I am trying to create a string that will allow me to set value a a particular position in the string.
    I am running a validation an have many for loops with various variable lengths being returned.
    I want the output to be formatted so that the status is lined up in the same postion.
    for example i check a list of directories to see if they exist and I want to display an OK or FAILED in the output. I want the output to look like something below.
    /IDS [ OK ]
    /VALID [ OK ]
    /DEVEL [FAILED]
    /PROGRAMS [ OK ]

    any help

  • Fox Dec 3, 2009 @ 15:33

    Hey !

    Thanks for the tip ! resolved my issue !
    Expr lenght was working under linux but not under Solaris.

    • velmani Feb 17, 2014 @ 14:17

      The command `expr length $var` is platform dependent.You can not run it in another platform rather than the Linux.But if you using the command `echo ${#var}`, you can run it in cross platform.

  • Patwari Jun 22, 2010 @ 11:55

    More options 😀

    myVar="nixcraft"
    echo ${#myVar}
    echo ${myVar} | awk ' { print length } '
    echo "${myVar}" | wc -c
    echo `expr length ${myVar}`
  • alhaizan Jul 6, 2010 @ 21:43

    Another simple way is:

    mystr="A random string by alhaizan"
    len=${#mystr}
    echo $len
  • Merry Patel Sep 14, 2010 @ 17:11

    I want program code for “Accept number and check the number is even or odd, finds the length of the number, sum of the digits in the number” in Unix.

    • Imtiyaz Jan 15, 2015 @ 5:21

      # to find Even or Odd
      echo “Enter the A value”;
      read A
      if [ `expr $A % 2` -eq 0 ]
      then
      echo “Number is even”;
      else
      echo “Number is odd”;
      fi

  • Vishal Jun 24, 2011 @ 6:06

    Hi All,

    I am looking for a script to compare the dates of two files to find out which one is newer.
    Taking the following files as reference:

    -rwxr-xr-x 1 vishy vishy 10088 Apr 26 11:08 file1
    -rwxrwxr-x 1 vishy vishy 3232 Feb 12 2009 file2

    We can see that for file1 the date and time(month date hrs:mins) is displayed, but for file2 month date and year is displayed.

    Can anyone please share a script to compare the dates of files of these kind?

    Regards,
    Vishy

  • hoawa Mar 7, 2012 @ 20:58

    what is the code for generating the number of char for A and B for unix and I want the input of the user to be prompted every time a input is done (e.g. loop)

    So I would want te program to allow the user to repeatedly input a string of characters and produce the list of number of each character in the string and generate the percentage of each character in the string.

    Any suggestions.

  • Preeti May 17, 2012 @ 9:57

    echo “enter 1se file name”
    read f1
    echo “enter 2nd fname”
    read f2
    if [ $f1 -nt -$f2 ]
    then
    echo ” $f1 is newer”
    else
    echo ” $f2 is newer”
    fi

  • Tom Mar 28, 2013 @ 20:19

    Just add this to your .bashrc:
    ——- cut ——-

    strlen() {
      str="$@"
      echo ${#str}
    }

    —— end cut ——
    Then all you need is:
    $ strlen This is some string
    19
    $ strlen "a"
    1

    ;]

  • Peter W Jun 20, 2013 @ 7:42

    One previous suggestion was:

    echo "${myVar}" | wc -c

    However this includes the trailing character so the length is out by 1.

    Using a generic expr command you can get the length on almost any platform or shell:

    expr "${myVar}" : '.*'
    • Imtiyaz Jan 15, 2015 @ 6:30

      Finding length of the string
      expr “abcd” : ‘.*’
      o/p 4

  • Samapika Tripathy Dec 4, 2013 @ 8:41

    thank you

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.