Definition and addition, deletion, modification and query of Shell array

Introduction to Shell Arrays


Why is Shell array generated?

Usually when developing a Shell script, variables are defined in the form "a=1;b=2;c=3", but what if there are multiple variables?

At this time, it will be very laborious to define one by one, and if there are multiple uncertain variable contents, it will be difficult to define variables. In addition, it is also very painful to quickly read the values ​​​​of different variables, so arrays were born. , it appeared to solve the above problems.

What is SheIl array


If readers have programming experience in other languages, they will be familiar with the concept of arrays. Simply put, Shell's array is a collection of elements. It names a limited number of elements (variables or character contents) with a name, and then uses numbers to distinguish them . This name is called the array name, and the number used to distinguish different contents is called the array subscript. The individual elements (variables) that make up an array are called elements of the array, sometimes also called subscript variables.

Shell array definition


There are many ways to define Shell arrays, as listed below.

Method 1: Use parentheses to enclose the variable value and assign it to the array variable, and separate each variable value with a space.

The syntax is as follows:
array=(valuel value2 value3...) This is a common definition method and needs to be mastered.

With the Shell array, you can use the same name to refer to a series of variables and variable values, and identify and use them by numbers (indexes). In many situations, using arrays can shorten and simplify program development.

 Method 2: Enclose the variable value in parentheses and assign it in the form of key-value pairs.

This method is in the form of a key-value pair. The corresponding number in the parentheses is the array subscript, and the content after the equal sign is the value of the array variable corresponding to the subscript. This method is relatively complicated and is not recommended.

Method 3: Define by defining array variables separately.

Method 4: Dynamically define array variables and use the output of the command as the contents of the array.

Guess you like

Origin blog.csdn.net/qq_34556414/article/details/132879653