Size: 1014
Comment: Mark which version works where; add awk version; cosmetics
|
Size: 1289
Comment: `length` is not the only problematic value for a variable argument to `expr`.
|
Deletions are marked like this. | Additions are marked like this. |
Line 28: | Line 28: |
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}}}. | This second version is not specified in [[POSIX]], so is not portable across all platforms. However, if {{{$varname}}} expands to any `expr` operator like `+` or `(` or `length`, the first version will fail. A portable way is: {{{ expr \( "X$varname" : ".*" \) - 1 }}} |
Line 35: | Line 41: |
}}} Though that one will fail for values of $varname that contain backslash characters, so you may prefer: {{{ # Bourne with POSIX awk awk 'BEGIN {print length(ARGV[1]);exit}' "$varname" |
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 any expr operator like + or ( or length, the first version will fail.
A portable way is:
expr \( "X$varname" : ".*" \) - 1
One may also use awk:
# Bourne awk -v x="$varname" 'BEGIN {print length(x)}'
Though that one will fail for values of $varname that contain backslash characters, so you may prefer:
# Bourne with POSIX awk awk 'BEGIN {print length(ARGV[1]);exit}' "$varname"
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.