Differences between revisions 4 and 7 (spanning 3 versions)
Revision 4 as of 2009-06-09 13:19:16
Size: 678
Editor: localhost
Comment: its about length.. it should also bring examples for arrays
Revision 7 as of 2011-03-01 00:03:52
Size: 1014
Editor: GreyCat
Comment: Mark which version works where; add awk version; cosmetics
Deletions are marked like this. Additions are marked like this.
Line 3: Line 3:
The fastest way, not requiring external programs (but usable only with [[BASH]] and KornShell): The fastest way, not requiring external programs (but not usable in Bourne shells):
Line 6: Line 6:
# POSIX
Line 12: Line 13:
# Bourne
Line 17: Line 19:
Another one: or:
Line 20: Line 22:
# Bourne, with GNU expr(1)
Line 23: Line 26:
(This is for a BSD/GNU version of {{{expr}}}. Do not use this, because it is not [[POSIX]]). (BSD/GNU {{{expr}}} only)

This second version is not specified in [[POSIX]], so is not portable across all platforms. However, if {{{$varname}}} expands to {{{"length"}}}, the first version will fail with BSD/GNU {{{expr}}}.

One may also use `awk`:
Line 26: Line 33:
# Bourne
awk -v x="$varname" 'BEGIN {print length(x)}'
}}}

------

Similar needs:

{{{
# Korn/Bash
Line 29: Line 46:
Returns the Number of Elements in an Array. Returns the number of elements in an array.
Line 32: Line 49:
# Korn/Bash
Line 35: Line 53:
Returns the length of the Arrays Element i. Returns the length of the array's element i.

----
CategoryShell

Is there a function to return the length of a string?

The fastest way, not requiring external programs (but not usable in Bourne shells):

# POSIX
${#varname}

or for Bourne shells:

# Bourne
expr "$varname" : '.*'

(expr prints the number of characters matching the pattern .*, which is the length of the string.)

or:

# Bourne, with GNU expr(1)
expr length "$varname"

(BSD/GNU expr only)

This second version is not specified in POSIX, so is not portable across all platforms. However, if $varname expands to "length", the first version will fail with BSD/GNU expr.

One may also use awk:

# Bourne
awk -v x="$varname" 'BEGIN {print length(x)}'


Similar needs:

# Korn/Bash
${#arrayname[@]}

Returns the number of elements in an array.

# Korn/Bash
${#arrayname[i]}

Returns the length of the array's element i.


CategoryShell

BashFAQ/007 (last edited 2015-03-05 00:24:26 by izabera)