Using Array Variables
Problem
There have been plenty of scripts so far with variables, but can bash deal with an array of variables?
Solution
Yes. bash now has an array syntax for single-dimension arrays.
Description
Arrays are easy to initialize if you know the values as you write the script. The format is simple:
MYRA=(first second third home)
Each element of the array is a separate word in the list enclosed in parentheses. Then you can refer to each this way:
echo runners on ${MYRA[0]} and ${MYRA[2]}
This output is the result:
runners on first and third
If you write only $MYRA
, you
will get only the first element, just as if you had written ${MYRA[0]}
.
See Also
Learning the bash Shell by Cameron Newham (O’Reilly), pages 157–161 for more information about arrays
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.