Find the answer to your Linux question:
Results 1 to 5 of 5
Hi, How to find the variable length in Shell. Ex: var=string the 'var' contains "string" of 6 char. so length is 6....
  1. #1
    Just Joined!
    Join Date
    Aug 2008
    Posts
    49

    Variable length in Shell

    Hi,

    How to find the variable length in Shell.
    Ex:

    var=string

    the 'var' contains "string" of 6 char. so length is 6.

  2. #2
    Linux Engineer GNU-Fan's Avatar
    Join Date
    Mar 2008
    Posts
    935
    Feed it to the wc command.
    Debian GNU/Linux -- You know you want it.

  3. #3
    Just Joined!
    Join Date
    Oct 2004
    Posts
    62
    With a little googling on "bash variable length"...
    Code:
     Using the ${#VAR } syntax will calculate the number of characters in a variable.

  4. #4
    Linux Newbie
    Join Date
    Feb 2009
    Posts
    99
    expr length $string

  5. #5
    Just Joined!
    Join Date
    Feb 2009
    Posts
    45
    Quote Originally Posted by dayananda.ms
    How to find the variable length in Shell.
    Ex:

    var=string

    the 'var' contains "string" of 6 char. so length is 6.
    I think itʼs worth noting that your question leaves open an important question: what is your definition of length?

    If you are refering the the byte length, then
    Code:
    $> echo -n "strüng" | wc -c
    7
    $> expr length "strüng"
    7
    will give you the right answer, just as according to «GNU-Fan» and «fiomba».

    If your definition of length is equivalent to the amount of intedended characters, then
    Code:
    $> echo -n "strüng" | wc -m
    6
    $> var="strüng"; echo ${#var};
    6
    will give you the expected answer (of course either of both commands depend on the LANG[UAGE] respectively LC_ALL environment variables), as already mentioned by «GNU-Fan» and «signmem».

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...