Array Initialization and Usage
With newer versions of bash, it supports one-dimensional arrays. An array can be explicitly declared by the declare shell-builtin.
But it is not necessary to declare array variables as above. We can insert individual elements to array directly as follows.
where ‘XX’ denotes the array index. To dereference array elements use the curly bracket syntax, i.e.
Note: Array indexing always start with 0.
Another convenient way of initializing an entire array is by using the pair of parenthesis as shown below.
There is yet another way of assigning values to arrays. This way of initialization is a sub-category of the previously explained method.
We can also read/assign values to array during the execution time using the read shell-builtin.
Now upon executing the above statement inside a script, it waits for some input. We need to provide the array elements separated by space (and not carriage return). After entering the values press enter to terminate.
To traverse through the array elements we can also use for loop.
The following script summarizes the contents of this particular section.
Various Operations on Arrays
Many of the standard string operations work on arrays . Look at the following sample script which implements some operations on arrays (including string operations).
Following is the output produced on executing the above script.
I think there is no significance in explaining the above script in detail as it is self-explanatory. If necessary I will dedicate one part in this series exclusively on string manipulations.
Command Substitution with Arrays
Command substitution assigns the output of a command or multiple commands into another context. Here in this context of arrays we can insert the output of commands as individual elements of arrays. Syntax is as follows.
By default the contents in the output of command separated by white spaces are plugged into array as individual elements. The following script list the contents of a directory, which are files with 755 permissions.
Simulating Two-dimensional Arrays
We can easily represent a 2-dimensional matrix using a 1-dimensional array. In row major order representation elements in each row of a matrix are progressively stored in array indexes in a sequential manner. For an mXn matrix, formula for the same can be written as.
Look at another sample script for adding 2 matrices and printing the resultant matrix.
No comments:
Post a Comment