Learn about Unix / Linux – Arrays and loops

Tram Ho

Today we will learn about arrays and loops in shell scripts. The concept of array is probably not unfamiliar to the coder brothers anymore, so we will ignore it.

Defines the values ​​in the array

1. Indirect definition

The indirect definition is that you will assign each value to each index of the array, for example:

2. Definition of mix

With this type, we can declare the array with a range of values, we can also add values ​​later if desired.

or

Access values

1. Get all values

To print out all the values ​​in the array, we use:

Result:

2. Get the value first

Result:

3. Get specific values

Result:

4. Get the value according to the string index

Result:

5. Specific value lengths

Result:

6. Array length

Result:

Loop

If there is an array, of course there will be a loop. Well one more thing about the operators in the shell, I forgot to write this article, so you can refer to another article temporarily ( link )

In a shell, there are four types of loops: while, for, until, select. As follows

While

The syntax of while loop is no different in the languages ​​that we often use, as long as the while condition is satisfied, the loop will continue to run.

Now we will create a loop that prints out the elements in an array

Result:

You can also have multiple nested loops

Result:

For

This is the loop that will traverse each element in the array

Result:

Until

This loop will run until a condition is met. For example, now I want to get the elements in the array with index <5, then the condition will be until index> 5

Result:

Select

Literally you will give the user a choice of an option and you will print the results of that option. Try the example below

Result:

Reference articles:

Share the news now

Source : Viblo