Bash Arrays: Difference between revisions
Line 59: | Line 59: | ||
==Use Cases== | ==Use Cases== | ||
===Read the Content of a File into An Array=== | |||
!!!Reading the content of a file in an array | |||
{{{ | |||
declare -a x; | |||
readarray < ./myfile.txt -t x; | |||
echo ${x[0]}; | |||
echo ${x[2]} | |||
}}} | |||
DO NOT | |||
{{{ | |||
cat ./myfile.txt | readarray | |||
}}} | |||
I found cases when this does not work. | |||
Alternative to research:<font color=red>'' The read builtin accepts a -a option to assign a list of words read from the standard input to an array, and can read values from the standard input into individual array elements. ''</font> | |||
=Associative Arrays= | =Associative Arrays= |
Revision as of 21:59, 23 February 2018
Internal
Indexed Arrays
External
- http://www.gnu.org/software/bash/manual/html_node/Arrays.html#Arrays
- http://tldp.org/LDP/abs/html/arrays.html
Overview
bash indexed arrays are 0-based and unidimensional. No explicit declaration is necessary if at least one element is initialized as described below:
Declaration
Arrays do not need explicit declarations, they will be automatically declared upon the first assignment of any of their elements.
my_array_var[0]="something"
They can be explicitly declared, though:
declare -a my_array_var
Previously declared arrays can be listed with:
declare -a
An array variable can be "undeclared" with "unset"
unset my_array_var
Assignment
Individual Elements
Individual elements are initialized by using ${var-name[index]}=value notation:
a[0]="something"
Entire Array
The (...) syntax can be used to initialize an entire array. The values must be separated by space:
a=("X" "Y" "Z")
If we want initialize only specific elements, we can use this syntax:
a=([0]="X" [4]="Y" [8]="Z")
Reference
Element arrays can be referenced with ${var-name[index]} notation:
echo ${a[0]}
If the array variable was not previously declared, or if the specific element was not initialized, a reference attempt will return the blank string.
Use Cases
Read the Content of a File into An Array
!!!Reading the content of a file in an array
{{{
declare -a x; readarray < ./myfile.txt -t x; echo ${x[0]}; echo ${x[2]}
}}}
DO NOT
readarray
I found cases when this does not work.
Alternative to research: The read builtin accepts a -a option to assign a list of words read from the standard input to an array, and can read values from the standard input into individual array elements.