Accessing the individual elements of a string assigned to a variable


As described in Dave Taylor's column in Linux Journal, one can access the individual characters of a string assigned to a shell variable using curly brackets and following the variable name with a colon and the desired starting position in the string. For example:
x=kingdom
echo ${x:3}
gdom

To limit the number of characters returned, use another colon and the number of desired characters:

echo ${x:4:2}
do

See also the ${!x*} in the Taylor article as well as Creating a shell variable name from a variable's value which also makes use of ${!x} notation.

01/18/2009