shell script - functions and arrays

1. Function

1.1 Function concept

1.1.1 Concept and advantages

Concept: A function is to define a function name, which can call function methods to complete convenient processing.

1.1.2 Rules for using functions

  • Directly write the function name when calling the function.
  • The last function with the same name takes effect.
  • Calling a function must be defined first
  • The order in which other functions are called does not matter as long as they are defined first.

1.2 How to use the function

1.2.1 Define function

method one

func_name (){
    
    
...函数体...
}

Method Two

function function_name {
    
    
# 函数体
}

Method three

function function_name() {
    
    
# 函数体
}

1.2.2 View function

declare -F #查看所有已定义的函数的函数名
declare -F func_name #查看指定函数的函数名

Insert image description here

declare -f
#查看所有已定义的函数的内容
declare -f func_name 
#查看指定函数的内容

Insert image description here

1.2.3 Call function

A function can only be called if it is defined

#先定义函数
function_name() {
    
    
# 函数体
}
#调用函数
function_name

Insert image description here

example

#定义函数
#!/bin/bash
 
os (){
    
    
if  grep -i -q "CentOS Linux 7 " /etc/os-release
then 
 echo "此操作系统是centos 7"
 
elif  grep -i -q "CentOS Linux 6 " /etc/os-release
then 
 echo "此操作系统是centos 6"
 
elif  grep -i -q "CentOS Linux 8 " /etc/os-release
then 
 echo "此操作系统是centos 8"
fi
}
 
#调用函数
os

Insert image description here

1.2.4 The return value of the function

return means exiting the function and returning an exit value. The $? variable can be used to display the value in the script.

Principles of use:

  • The return value is taken as soon as the function ends, because the $? variable only returns the exit status code of the last command executed.
#!/bin/bash
test1 () {
    
    
        read -p "请输入一个数字:" num
        return $[$num*2]
}
test1
echo $?

Insert image description here

  • The exit status code must be 0~255. When exceeded, the value will be divided by 256 and the remainder will be taken.
#!/bin/bash
test1 () {
    
    
        read -p "请输入一个数字:" num
        echo $[$num*2]
}
result=`test1`
echo $result

Insert image description here

The function of return value:

  • Judge and process the results of function execution: functions can return different values ​​to represent different execution statuses or error conditions.
  • Pass the result of function execution to other parts: the return value of the function can be assigned to a variable, and the calculation result of the function can be passed to other commands or used again.
  • As the exit status code of the script: Set different exit status codes according to different return values.

1.2.5 Function parameter passing

In the shell, parameters can be passed to functions when they are called. Inside the function body,
the value of the parameter is obtained in the form of $n. For example, $1 represents the first parameter, $2 represents the second parameter...that is, positional parameters are used to implement parameter transfer.

Sample script

  • Internal parameter transfer
    Insert image description here
  • External parameters
    Insert image description here
  • example
#!/bin/bash
add ( ) {
    
    
num=$[$1+$2]
}
num=0
read -p "请输入第一个数:"a

read -p "请输入第一个数:"b
#调用函数
add $a $b
echo "$num"

Insert image description here
Insert image description here

1.2.6 Delete function

unset function_name
#Delete the specified function from the current Shell environment

Insert image description here
Insert image description here

1.3 Function scope

  • Functions in shell scripts are only valid in the current shell environment
  • Variables in shell scripts are globally valid by default
  • Limit the variable to the inside of the function using the local command

Insert image description here
Insert image description here

1.4 Function files

Write the function code into a script file and call the script file when needed, which is equivalent to calling the function directly.
When using a function file in a shell script, you need to write the absolute path of the function file.

1.5 Recursive functions (important)

A recursive function refers to a function that calls itself within the function body and is used in scenarios where the same or similar tasks need to be performed repeatedly.
When writing a recursive function, be sure to set the end condition of the recursion to avoid an infinite loop.

factorial

fact() {
    
    
  if [ $1 -eq 1 ]
  then
    echo 1
  else
   local temp=$[$1 - 1]
   local result=$(fact $temp)
   echo $[$1 * $result]
		#  5 * $result(4*$result(3*$result(2*$result(1))))
  fi
}
read -p "请输入:" n
result=$(fact $n)
echo $result

Insert image description here

2. Array

2.1 What is an array?

  • Multiple values ​​can be stored in an array. Bash Shell only supports one-dimensional arrays (multi-dimensional arrays are not supported), and there is no need to define the array size during initialization (similar to PHP).
  • Like most programming languages, array elements are indexed starting from 0.
  • Shell arrays are represented by parentheses, and elements are separated by "space" symbols.
  • In a shell statement, when using or traversing an array, the array format should be written as ${arr[@]} or ${arr[*]}

2.2 Array format

Format one:

数组名=(value1 value2 ... valuen)
arr_number=(1 2 3 4 5 6 7 8 9)

Format two:

数组名=([0]=value0 [1]=value0 [2]=value0 ...)
arr_number=([0]=1 [1]=2 [2]=3 [3]=4)

Format three:

列表名:“value1 value2 valueN ..."
数组名=($列表名)
list_number="1 2 3 4 5 6"
arr_number=($list_number)

Format four:

数组名[0]="value"
数组名[1]="value"
数组名[2]="value"
arr_number[0]=1
arr_number[1]=2
arr_number[2]=3

2.3. The data type of the array

  • value type
  • character type
  • Use " " (double quotes) or ' ' (single quotes) to define
    an array that can be either numeric or mixed.
    Insert image description here

2.4 Get the length of the array

echo ${
    
    #数组名[*]} 
echo ${
    
    #数组名[@]} 

Insert image description here

2.5 Get the data list of the array

echo ${
    
    数组名[*]}
echo ${
    
    数组名[@]}

Insert image description here

2.6 Get the value corresponding to the array subscript

数组名=(元素0  元素1  元素2  ……)	//定义数组
echo ${
    
    数组名[索引值]}	//输出数组索引值对应的元素,索引值为从0开始

Insert image description here

2.7 Common operations of arrays

2.7.1 Array traversal

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

Insert image description here

2.7.2 Array slicing

a=(0 1 2 3 4 5 6 7 8)
echo "输出整个数组: " ${
    
    a[@]}
echo "取出数组1到3: " ${
    
    a[@]:1:3}
echo "取出数组5到后面所有的元素: " ${
    
    a[@]:5:5}

Insert image description here

2.7.3 Array replacement#Temporary replacement

echo ${
    
    a[@]/原替换位置/替换内容} 
 
#重新赋值,可以永久修改
a=(${
    
    a[@]/原替换位置/替换内容})

Insert image description here

2.7.4 Array deletion and deletion of specified subscript values

#删除整个数组
unset 数组名
 
#删除指定下标的值
unset 数组名[数组下标]

Insert image description here

2.7.5 Adding elements to an array

Method 1: Directly use subscripts to append elements

数组名[下标]=变量

Insert image description here

Method 2: Use the length of the array as a subscript to append elements

数组名[${
    
    数组名[#@]}]=变量名

Insert image description here

Method 3: Use += to append

数组名+=(变量1 变量2 ...)

Insert image description here

2.7.6 ​​​​​​​declare -a: View all arrays

Insert image description here

3. Bubble sorting

#!/bin/bash
#排序之前的数组顺序
a=(10 40 33 30 77 66 44 ) 
#确定循环比较的次数
for ((j=1;j<${
    
    #a[@]};j++))
do
#对比获取每次的最大元素的索引位置
for ((i=0;i<${
    
    #a[@]}-j;i++))
do
#如果对比出最大元素,就把该元素赋值给后面的变量tmp
if  [ ${
    
    a[$i]} -gt ${
    
    a[$i+1]} ]
then
#定义一个变量tmp,将每次比较的最大数值放进tmp,实现变量对换
tmp=${
    
    a[$i+1]}
a[$i+1]=${
    
    a[$i]}
a[$i]=$tmp
fi
done
done
echo ${
    
    a[*]} 

Insert image description here

Guess you like

Origin blog.csdn.net/m0_62231324/article/details/132392769