How to use shel function and Array
What this article shares with you is about how to use shel functions and arrays. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Shell function
Write the sequence of commands together in format
It is convenient to reuse the command sequence.
Shell function definition
[function] function name () {Command sequence [return x]}
You can use return or exit to end the function explicitly (using return to return the status code and echo to return the value)
The method of calling the function:
Function name [parameter 1] [parameter 2]
An example of the application of shell function:
1. Summation of two numbers
Define a function through sum () {}
Use the read command to interactively enter two numbers and sum them
2. Write user-defined functions that can be used after logging in to the system
Edit user-defined function file / test/function.sh
Load the executable function file / test/function.sh in the current Shell
Add the source / test/function.sh command to the ~ / .bashrc file
Shell array
Application scenarios include:
Get the length of the array
Get element length
Ergodic element
Element slicing
Element substitution
Element deletion
Array definition method
Method 1
Array name = (value0 value1 value2... )
Method 2
Array name = ([0] = value [1] = value [2] = value... )
Method 3
List name = "value0 value1 value2 …"
Array name = ($list name)
Method 4
Array name [0] = "value"
Array name [1] = "value"
Array name [2] = "value"
...
The data types included in the array
Numerical type
Character type
Operation of shell array
Get the length of the array
${Array name [@ / *]}
[root@localhost ~] aaa= (1 2 3 45) [root@localhost ~] bbb=$ {# aaa [*]} [root@localhost ~] echo $bbb5
Read a subscript assignment
${Array name [subscript]}
[root@localhost ~] # aaa= (1 2 3 45) [root@localhost ~] # bbb=$ {aaa [1]}) [root@localhost ~] # echo bbb2
Array traversal
[root@localhost test] # for ccc in ${aaa [@]} > do > echo $ccc > done1234
Enter 5 values at random and output the maximum value
#! / bin/bashfor