shell script functions, arrays and bubble sorting

Posted by A584537 on Wed, 09 Feb 2022 20:47:16 +0100

catalogue

1, shell function

1.1. Definition of function

(1) Format of function

(2) Function return value

1.2. Function call

1.3.return

1.4. Parameter passing of function

1.5. Scope of function

1.6. Local and global variables

1.7. Case of function

Factorial

Build local warehouse

2, Array

2.1. Definition of array

2.2. Array representation

2.3. Common usage of array

(1) Gets the length of the array

(2) Array element traversal

(3) Element slice

(4) Array element replacement

(5) Array deletion

III. bubble sorting

(1) Definition

(2) Bubble sort case

1, shell function

1.1. Definition of function

(1) Format of function

①
function Function name {
command
} 
     

②
Function name (){     
command
} 

(2) Function return value

Return means to exit the function and return an exit value. You can use $? Variable displays the value.

Use principle:

  • Take the return value as soon as the function ends, because $? Variable returns only the exit status code of the last command executed.
  • The exit status code must be 0 ~ 255, and the value beyond the limit will be 256.

1.2. Function call

Directly define the code block of the function in the script and write the function name to complete the call.

#!/bin/bash
function fun1 {     //Defines a function called fun1
echo "this is a function!"    //The function body is used to print "this is a function!"!
}

fun1    //Writing the function name directly will run the code in the function body (calling the function)

Note ①: the function name must be unique. If you define one first and then define it with the same name, the second one will overwrite the function of the first one, and there will be results you don't want, so you must be careful not to duplicate the name here.

#!/bin/bash
f1 (){
echo hello
}

f1 (){
echo world
}

f1

[root@localhost ~]# . f1.sh 
world

Note ②: the function must be defined before calling.

#!/bin/bash
f1 (){
echo hello
}


f3 (){
echo "$(f1) $(f2)"
}



f2 (){
echo world
}

f3

[root@localhost ~]# bash f1.sh / / because f2 is called in the f3 function, the definition of f2 cannot be known when f3 is called. Because f2 is not defined until f3 runs, the running script will report an error.
f1.sh:Line 8: f2: Command not found
hello 

Note ③: it is not necessary to define the function at the beginning of the script, as long as it is defined before calling.

1.3.return

Case 1:

The first method uses return to return a value:

#!/bin/bash
function test1 {
read -p "Please enter a number" num
return $[$num*2]
}
test1
echo $?

The second echo directly outputs a value:

#!/bin/bash
test2 () {
read -P "Please enter a value of 2:" NUM
echo $[$NUM*2]
}
res=$(test2)
echo $[$res *2]

Case 2: does the test file exist

#!/bin/bash
file=/etc/xxxx

f1 (){
if [ -f $file ];then
return 100
else
return 200
fi
}

f1
echo $?   //We can judge the result we want according to the return value. If it is 100, it means it exists; if it is 200, it means it does not exist.

1.4. Parameter passing of function

Example 1: sum two numbers.

#!/bin/bash 
sum(){
read -p "Please enter the first number:" NUM1 
read -p "Please enter the second number:" NUM2
echo "The two numbers you entered are: $NUM1 and $NUM2 "
SUM=$(( NUM1+$NUM2))
echo "The sum of the two numbers is: $SUM"
}
sum

Operation results:


Example 2: calculate the sum of location variables $1 and $2.

Parameters of function:

#!/bin/bash
add (){
let sum=$1+$2   //The location variable here is the location variable of the function, so it should be written after the calling function. If it is used when calling the script, it cannot succeed.
echo $sum
}

add 4 5

Script parameters:

#!/bin/bash
add (){
let sum=$1+$2
echo $sum
}

add $1 $2   //This is equivalent to calling the parameters of the script, and then passing the location variable of the script to the function for calculation

1.5. Scope of function

In a Shell script, the execution of a function does not open a new sub Shell, but is only valid in the currently defined Shell environment. If the variables in the Shell script are not specially set, they are valid in the whole script by default. When writing scripts, it is sometimes necessary to limit the value of variables within functions, which can be realized through the built-in command local. The use of function internal variables can avoid the influence of variables with the same name inside and outside the function on the script results.

Variables in shell scripts are valid globally by default.
local command: restrict variables to functions.

Case 1:

#!/bin/bsah
myfun ()
{
local i 
i=8 
echo $i
}
i=9 
myfun 
echo $i

Operation results:

In the above script, the local command is used inside the myfun function to set the variable i, which is used to limit the variable i inside the function. The external variable i of myfun function is also defined, and the internal variable i and the global variable i do not affect each other. When the script executes, the function myfun is called first, and the internal variable i of the function is 8, so the output result is 8. After calling the function, assign 9 to the variable i, and then print the external variable i, so 9 is output again.

Case 2:

#!/bin/bash
myfunc() {
a=8 
echo $a
}
myfunc
echo $a

Operation results:

 1.6. Local and global variables

  • Variables defined in the script or not declared as local variables in the function body are global variables, which means they are recognized in the current shell environment.
  • If you need this variable to be used only in the function, you can declare it with the local keyword in the function. In this way, it doesn't matter even if there is a variable with the same name outside the function, and it doesn't affect its use in the function body.
  • If you execute the script with source, you can see the difference.

Case 1:

[root@localhost ~]# a=nihao
#!/ bin/bash / / write a function, first print the value of a, then change the value of a, and then print
f1 (){
echo $a
a=world
echo $a
}

f1
[root@localhost ~]# source f1.sh / / execute the script with source, and you will find that the value of a has changed
nihao
world
[root@localhost ~]# echo $a
world

Case 2: define the value of variable a with local in the function body.

#!/bin/bash
f1 (){
echo $a
local a=world
echo $a
}

f1
[root@localhost ~]# source f1.sh / / execute the script and find that the value of a has not changed
world
world

Case 3:

#!/bin/bash
f1 (){
echo $a
local a=world
echo $a
}

f1
echo $a

[root@localhost ~]# a=hello
[root@localhost ~]# source f1.sh / / the value of variable a can be regarded as a local variable in the function body, so it only takes effect in the function body
hello
world
hello

1.7. Case of function

Factorial

The first method:

#!/bin/bash
jiecheng (){
cheng=1
for i in {1..6}
do
let cheng=$i*$cheng
done
echo $cheng
}

jiecheng

The second method: optimized version: calculate the factorial of several according to the needs of users.

#!/bin/bash
jiecheng (){
cheng=1
read -p "What factorial do you want to calculate" num   //① Prompt the user for input
for i in `seq $num`
do
let cheng=$i*$cheng
done
echo $cheng
}

jiecheng

The third method:

#!/bin/bash
jiecheng (){
cheng=1
for i in `seq $1`    //② By means of position variables
do
let cheng=$i*$cheng
done
echo $cheng
}

jiecheng $1

Build local warehouse

 

2, Array

2.1. Definition of array

An array is a collection of data of the same type. It opens up a continuous space in memory and is usually used in conjunction with recycling.

Classification of arrays

  • Ordinary array: directly defined without declaration, and the subscript index can only be an integer.
  • Associative array: it needs to be declared with declare -A, otherwise the system will not recognize it, and the index can be a string.

How arrays are defined

(30 20 10 60 50 40)

    0    1   2   3   4   5

Data types included in the array

  • value type
  • Character type

(defined with "" or ')

2.2. Array representation

The first one: directly enclose the elements to be added to the array in parentheses, separated by spaces.

num=(11 22 33 44)

${#num} displays the length of the string
 Array name=(value0 value1 value2)

The second method: define a value for each index and add it into the array. The index numbers can be discontinuous.

num=([0]=55 [1]=66 [2]=77 [4]=88)

Array name=([0]=value [1]=value [2]=value)

The third method: first assign all the elements to be added to the array to a variable, and then reference this variable to add it to the array.

list="11 12 13 14"

num=($list)
List name="value0 value1 value2..."
Array name=($List name)

The fourth one is defined by subscript

Array name[0]="11"
Array name[1]="22"
Array name[2]="33"

Array name[0]="value"
Array name[1]="value"
Array name[2]="value"

2.3. Common usage of array

(1) Gets the length of the array

 

(2) Array element traversal

#!/bin/bash
arr=(1 2 3 4 5 6)
for i in ${arr[*]}   perhaps for i in ${arr[@]}
do
echo $i
done

(3) Element slice

(4) array element replacement

Temporary replacement

Permanent replacement

 

(5) Array deletion

Delete the entire array:

Delete the fifth element of the array:

III. bubble sorting

(1) Definition

Similar to the action of bubble upwelling, the data will be continuously moved forward from small to large or from large to small in the array.

Basic idea:
The basic idea of bubble sorting is to compare the values of two adjacent elements. If the conditions are met, exchange the element values. Move the smaller element to the front of the array and the larger element to the back of the array (that is, exchange the positions of the two elements). In this way, the smaller element rises from the bottom to the top like an air bubble.

Algorithm idea:
The bubbling algorithm is realized by a double-layer loop, in which the external loop is used to control the number of sorting rounds. Generally, the length of the array to be sorted is reduced by one time, because there is only one array element left in the last loop, and there is no need to compare. At the same time, the array has been sorted. The internal loop is mainly used to compare the size of each adjacent element in the array to determine whether to exchange positions. The number of comparisons and exchanges decreases with the number of sorting rounds.

(2) Bubble sort case

Example: sort 100, 50, 30, 60, 20 and 50 by bubble sorting.

Topics: shell