I have long used code similar to :
string="abc 123 xyz"
fields=( ${string} )
echo "The 3rd field = ${fields[2]}"
to break a string into fields and reference a particular element within the string.
But I ran into a strange use case today where the source string contained an '*' asterisks character. ie:
string="abc * xyz"
fields=( ${string} )
echo "The 3rd field = ${fields[2]}"
declare -p fields
In this case, the '*' does not map into the array literally, rather it appears to get expanded to a list of environment variables, and the array ends up with a much larger list or values that do not represent the original string.
Three questions:
- What exactly is * being expanded to?
- Can this expansion be disabled so the code will behave in the intended fashion?
- Is there a better way to accomplish the transformation of a string into an array of tokens that do not suffer from this side effect?