Size: 678
Comment: its about length.. it should also bring examples for arrays
|
Size: 830
Comment: what if $varname == "length" :-(
|
Deletions are marked like this. | Additions are marked like this. |
Line 17: | Line 17: |
Another one: | or: |
Line 23: | Line 23: |
(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}}}. |
Line 36: | Line 40: |
---- 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.