Today, let's look at the Linux array:
First, what is array?
Array: Actually, the group is also a variable, but it is a variable that can save multiple values. The index and subscript of the array are used for reference.
Note: The values stored in the array are generally of the same type, but each value is independent. Can be used or managed independently.
So how to initialize an array?
Initialization Method ①: Separate Initialization
Names [2] = aaa defines AAA as the 3rd elements of the array names
Names [0] = BBB defines BBB as the 1st elements in the group
Here we found that the arrays are numbered from scratch. Generally, when declaring a group, it can also start from 1, but when you declare it as 1, 0 actually exists.
Initialization Method ②: Multiple initialization at the same time: enclose them in parentheses!
Names = ([2] = aaa [0] = BBB [1] = CCC)
In this way, the 3rd elements of the names group are directly defined as AAA, 1st elements are BBB, and 2nd elements are CCC.
For groups that are about to be defined with clearly known order, we can initialize multiple groups at a time.
Names = (bbb ccc AAA)
In this example, the 1st position of the array is BBB 2nd, the CCC position is, and the third position is AAA.
If you want to skip a page missing in the middle of the sorting, you can directly assign values to the following. Use:
Names = (AAA [5] = bbb ccc)
Then, the group's 1 is AAA 6 is BBB 7 is ccc
Note: page skipping can only be skipped once. Skip multiple times is not recognized.
Initialization Method ③: one-time initialization using cyclic scripts
Sometimes our group needs to be each line in a file or each line shown. What should we do?
#! /Bin/bash
Let I = 0
For file in 'ls/var'; do
Varfile [$ I] = $ File
Let I ++
Done
By using this script, the names of each file under "ls/Var" are assigned to the array varfile.
How can we call a value after it is assigned?
Take the initialization method ③ as an example:
When calling an array variable, use
Echo $ {varfile [0]} because we want to reference an array, an element in the reference group must be enclosed in parentheses to indicate which one we want to reference, therefore, braces must be used for Array variables.
How do I reference all values in the array?
Echo $ {varfile [@]}
Echo $ {varfile [*]}
The above two methods can reference all values of a group, but there are some differences. In fact, if you change the default delimiter to a non-space character, you can see that there are no too many descriptions here.
Echo $ {# varfile [*]}
Add the # sign to the front to display the number of groups.
========================================================== ==========
Okay. I believe you should use arrays ~ Let's start a question and practice the use of arrays !!
Write a script to randomly display one of the eight country names.
Basic Format
Let a = 0
While [$ A-le 10]; do
Echo $ {random % 8}
Let a ++
Done