Differences between revisions 6 and 9 (spanning 3 versions)
Revision 6 as of 2011-02-28 22:27:41
Size: 830
Editor: 203-214-41-227
Comment: what if $varname == "length" :-(
Revision 9 as of 2011-05-26 13:28:27
Size: 1280
Editor: sbl-eh4-rp1
Comment:
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 20: Line 22:
# Bourne, with GNU expr(1)
Line 25: Line 28:
This second version is not specified in [[POSIX]], so is not portable across all platforms. 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 27: Line 30:
However, if {{{$varname}}} expands to {{{"length"}}}, the first version will fail with BSD/GNU {{{expr}}}. A portable way is:
Line 30: Line 33:
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
Line 33: Line 59:
Returns the Number of Elements in an Array. Returns the number of elements in an array.
Line 36: Line 62:
# Korn/Bash
Line 39: Line 66:
Returns the length of the Arrays Element i. Returns the length of the array's element i.

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.

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.


CategoryShell

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