Differences between revisions 1 and 6 (spanning 5 versions)
Revision 1 as of 2007-05-02 22:51:12
Size: 484
Editor: redondos
Comment:
Revision 6 as of 2011-02-28 22:27:41
Size: 830
Editor: 203-214-41-227
Comment: what if $varname == "length" :-(
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
[[Anchor(faq7)]] <<Anchor(faq7)>>
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 usable only with [[BASH]] and KornShell):
Line 8: Line 9:
or or for Bourne shells:
Line 14: Line 15:
({{{expr}}} prints the number of characters matching the pattern {{{.*}}}, which is the length of the string) ({{{expr}}} prints the number of characters matching the pattern {{{.*}}}, which is the length of the string.)
Line 16: Line 17:
or or:
Line 22: Line 23:
(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}}}.

{{{
${#arrayname[@]}
}}}

Returns the Number of Elements in an Array.

{{{
${#arrayname[i]}
}}}

Returns the length of the Arrays Element i.

----
CategoryShell

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

The fastest way, not requiring external programs (but usable only with BASH and KornShell):

${#varname}

or for Bourne shells:

expr "$varname" : '.*'

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

or:

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.

${#arrayname[@]}

Returns the Number of Elements in an Array.

${#arrayname[i]}

Returns the length of the Arrays Element i.


CategoryShell

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