当前位置:网站首页>Functions and arrays of shell scripts
Functions and arrays of shell scripts
2022-07-04 01:02:00 【Wozkid】
One 、shell function
1.1 Function function
1. A statement block is defined as a function approximately equal to an alias , Defined function , Rereference function
2. Encapsulated, reusable, functional code
1.2 The basic format of the function
Format 1:
function Function name {
command
} ### This is a standard way of writing
Format 2:
Function name (){
command
} ### Most commonly used because of the most concise
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
1.3 Function call
Directly define the code block of the function in the script and write the function name to complete the call
Example :
[[email protected] ~]# vim kk.sh
#!/bin/bash
function f { ### Define a function called f
echo "hello world!" ### The function is to print “hello world!”
}
f ### Writing the function name directly will run the code in the function
[[email protected] ~]# sh kk.sh
hello world!
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
notes : Function name must be unique , If you define a , Use the same name to define , The second will override the function of the first , There are results you don't want , So be careful not to duplicate your name here !
[[email protected] ~]# vim kk.sh
#!/bin/bash
f1 () {
echo "hello"
}
f2 () {
echo "world"
}
f3 () {
echo "$(f1) $(f2)"
}
f3
[[email protected] ~]# sh kk.sh
hello world
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
1.4 The return value of the function
return Represents the exit function and returns an exit value , You can use $? The variable represents the value
The principle of using functions :
1. Take the return value as soon as the function ends , because $? Variable returns only the exit status code of the last command executed ;
2. Exit status code must be 0~255, When exceeded, the value will be divided by 256 Remainder .
Example :
[[email protected] ~]# vim kk.sh
#!/bin/bas
user () {
if [ $USER = root ]
then
echo " This is the administrator user "
else
echo " This is not an administrator user "
return 1
fi
}
user
[[email protected] ~]# sh kk.sh
This is the administrator user
[[email protected] ~]# echo $?
0
[[email protected] ~]# su lu
[[email protected] ~]$ sh kk.sh
This is not an administrator user
[[email protected] ~]$ echo $?
1
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
1.5 Arguments to functions
stay Shell in , You can pass parameters to a function when you call it . Inside the body of the function , adopt $n To get the value of the parameter , for example ,$1 Represents the first parameter ,$2 Represents the second parameter … That is to use position parameters to realize parameter transfer .
Example :
Sum two numbers
[[email protected] ~]# vim kkk.sh
#!/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 two numbers is :$sum"
}
sum
[[email protected] ~]# sh kkk.sh
Please enter the first number :6
Please enter the second number :66
The two numbers you entered are : 6 and 66
The sum of two numbers is :72
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
Case study :
Factorial
[[email protected] ~]# vim kkk.sh
#!/bin/bash
jc () {
che=1
for i in {1..5}
do
let che=$i*$che
done
echo $che
}
jc
[[email protected] ~]# sh kkk.sh
120
Optimized version : Calculate the factorial of several orders according to the demand
[[email protected] ~]# vim kkk.sh
#!/bin/bash
jc () {
che=1
read -p " Please enter the factorial you want to calculate :" num
for i in `seq $num`
do
let che=$i*$che
done
echo $che
}
jc
[[email protected] ~]# sh kkk.sh
Please enter the factorial you want to calculate :5
120
[[email protected] ~]# sh kkk.sh
Please enter the factorial you want to calculate :6
720
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
1.6 Local and global variables
Variables defined in the script or not declared as local variables in the function body are global variables , It means at present shell The environment recognizes
If you need this variable to be used only in the function, you can use... In the function local Keyword declaration , In this way, even if there is a variable with the same name outside the function, it doesn't matter , It does not affect the use in the function body
If it is to use source If you execute the script, you can see the difference
To call a command externally, you need to first source once . And then call the function. , Then call the variable in the function
[[email protected] ~]# a=hello
[[email protected] ~]# vim kkkk.sh
#!/bin/bash
f1 () {
echo $a
a=world
echo $a
}
f1
[[email protected] ~]# source kkkk.sh ### use source Execute the script , Will find a The value of
hello
world
[[email protected] ~]# echo $a
world
Use... In the body of a function local Defining variables a Value
[[email protected] ~]# vim kkkk.sh
#!/bin/bash
f1 () {
echo $a
local a=world
echo $a
}
f1
[[email protected] ~]# source kkkk.sh ### Execute script discovery a The value of
world
world
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
1.7 Recursion of a function
The function itself calls itself
List the files in the directory , The catalogue is shown in blue , The file displays hierarchical relationships
[[email protected] ~]# vim kkkk.sh
#!/bin/bash
list(){
for i in $1/*
do
if [ -d $i ];then
echo -e "\e[34m$i\e[0m"
list $i " $2"
else
echo "$2$i"
fi
done
}
list $1 $2
[[email protected] ~]# sh kkkk.sh /home
/home/kk
/home/kk/*
/home/lu
/home/lu/ public
/home/lu/ public /*
/home/lu/ Templates
/home/lu/ Templates /*
/home/lu/ video
/home/lu/ video /*
/home/lu/ picture
/home/lu/ picture /*
/home/lu/ file
/home/lu/ file /*
/home/lu/ download
/home/lu/ download /*
/home/lu/ music
/home/lu/ music /*
/home/lu/ desktop
/home/lu/ desktop /*
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
Two 、 Array
2.1 shell Definition of array
1. You can store multiple values in an array .Bash Shell Only one-dimensional arrays are supported ( Multidimensional arrays are not supported )
2. The subscripts of array elements are 0 Start .
3.Shell Arrays are represented in parentheses , Element use " Space " Symbol split
4. stay shell In the sentence , Use 、 When traversing an array , The array format should be written as ${arr[@]} or ${arr[*]}
An array is a collection of data of the same type , It opens up a continuous space in memory , Usually used together with recycling
The classification of arrays :
Normal array : Direct definition without declaration , Subscript index can only be an integer
Associative array : Need to use declare -A Statement Otherwise the system doesn't recognize , The index can be a string
2.2 How to define an array
The first one is : Directly enclose the elements to be added to the array in parentheses , Separate... With spaces in the middle
num= ( 11 22 33 44 )
${ #num} Shows the length of the string
Array name =(value0 value1 value2)
The second kind : Precisely define a value for each subscript index and add it to the array , Index numbers can be discontinuous
num= ( [ 0 ]=55 [ 1 ]=66 [ 2 ]=77 [ 4 ]=88)
Array name =( [ 0 ]=value [ 1 ]=value [ 2 ]=value. . . )
The third kind of : First assign all the elements to be added to the array to a variable , Then reference this variable and add it to the array .
list="11 12 13 14"
num=($list)
List name ="value0 value1 value2..."
Array name =($ List name )
A fourth : Define according to the 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"
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
2.3. Common usage of array
1. Gets the length of the array
[[email protected] ~]# ar_number=(10 20 30 40 50)
[[email protected] ~]# ar_length=${#ar_number[*]}
[[email protected] ~]# echo $ar_length
5
[[email protected] ~]# ar_number=(10 20 30 40 50)
[[email protected] ~]# ar_length=${#ar_number[@]}
[[email protected] ~]# echo $ar_length
5
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
2. Array element traversal
[[email protected] ~]# vim kkkk.sh
#!/bin/bash
arr=(1 2 3 4 5 6)
for i in ${arr[*]} ### or for i in ${arr[@]}
do
echo $i
done
[[email protected] ~]# sh kkkk.sh
1
2
3
4
5
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
3. Element slice
[[email protected] ~]# arr=(1 2 3 4 5 6)
[[email protected] ~]# echo ${arr[*]}
1 2 3 4 5 6
[[email protected] ~]# echo ${arr[*]:2:3}
3 4 5
[[email protected] ~]# echo ${arr[*]:2:4}
3 4 5 6
[[email protected] ~]# echo ${arr[*]:0:5}
1 2 3 4 5
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
4. Array element replacement
A temporary replacement
[[email protected] ~]# arr=(1 2 3 4 56 7 8)
[[email protected] ~]# echo ${arr[*]}
1 2 3 4 56 7 8
[[email protected] ~]# echo ${arr[*]/56/5 6}
1 2 3 4 5 6 7 8
[[email protected] ~]# echo ${arr[*]}
1 2 3 4 56 7 8
Permanently replace
[[email protected] ~]# arr=(1 2 3 4 56 7 8)
[[email protected] ~]# echo ${arr[@]}
1 2 3 4 56 7 8
[[email protected] ~]# arr=(${arr[@]/56/5 6})
[[email protected] ~]# echo ${arr[@]}
1 2 3 4 5 6 7 8
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
5. Array delete
Delete the entire array
[[email protected] ~]# arr=(1 2 3 4 56 7 8)
[[email protected] ~]# echo ${arr[@]}
1 2 3 4 56 7 8
[[email protected] ~]# unset arr
[[email protected] ~]# echo ${arr[@]}
[[email protected] ~]#
Delete the elements in the array
[[email protected] ~]# arr=(1 2 3 4 5 6 7 8)
[[email protected] ~]# echo ${arr[@]}
1 2 3 4 5 6 7 8
[[email protected] ~]# unset arr[7]
[[email protected] ~]# echo ${arr[@]}
1 2 3 4 5 6 7
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
3、 ... and 、 Bubble sort
1. Definition :
It's like a bubble rising , Will move the data in the array from small to large or from large to small
2. The basic idea :
The basic idea of bubble sorting is to compare the values of two adjacent elements , Exchange element values if conditions are met , Move the smaller elements to the front of the array , Move large elements to the back of the array ( That is, to exchange the positions of two elements ), So the smaller elements rise from the bottom to the top like bubbles
3. Algorithm ideas :
The bubble algorithm is implemented by a two-layer loop , The external loop is used to control the number of sorting rounds , Generally, the length of the array to be sorted minus 1 Time , Because there's only one array element left in the last loop , There's no need to compare , At the same time, the array has finished sorting . The inner loop is mainly used to compare the size of each adjacent element in the array , To determine whether to swap positions , The number of comparisons and exchanges decreases with the number of sorting rounds
4. Bubble sort case :
#!/bin/bash
# Defining variables
ar=(90 30 60 20 70 10)
echo " Before ordering :${ar[*]}"
lt=${#ar[*]}
# Define the number of comparison rounds , The number of rounds is the length of the array -1, from 1 Start
for ((i=1;i<$lt;i++))
do
# Confirm the position of the comparison element , Compare adjacent elements , Larger move back , The number of comparisons decreases with the number of rounds
for ((l=0;l<$lt;l++))
do
# Define the value of the first element
first=${ar[$l]}
# Define the value of the second element
k=$[$l+1]
two=${ar[$l]}
# If the first element is larger than the second, swap positions
if [ $first -gt $two ]
then
# Save the first element in a temporary variable
temp=$first
# Assign the value of the second element to the first element
ar[$l]=$two
# Assign a temporary variable to the second element
ar[$k]=$temp
fi
done
done
echo " After ordering :${ar[*]}"
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
边栏推荐
- Regular expression of shell script value
- Delete all elements with a value of Y. The values of array elements and y are entered by the main function through the keyboard.
- Oracle database knowledge points that cannot be learned (III)
- Cloud dial test helps Weidong cloud education to comprehensively improve the global user experience
- 1-Redis架构设计到使用场景-四种部署运行模式(上)
- Why use get/set instead of exposing properties
- Print diamond pattern
- 基于.NetCore开发博客项目 StarBlog - (14) 实现主题切换功能
- gslb(global server load balance)技术的一点理解
- Self study software testing. To what extent can you go out and find a job?
猜你喜欢

Employees' turnover intention is under the control of the company. After the dispute, the monitoring system developer quietly removed the relevant services

Characteristics of ginger

我管你什么okr还是kpi,PPT轻松交给你

Analysis and solution of lazyinitializationexception

Cloud dial test helps Weidong cloud education to comprehensively improve the global user experience

What is regression testing? Talk about regression testing in the eyes of Ali Test Engineers

CLP information - how does the digital transformation of credit business change from star to finger?

Function: find the sum of the elements on the main and sub diagonal of the matrix with 5 rows and 5 columns. Note that the elements where the two diagonals intersect are added only once. For example,

Introduction to unity shader essentials reading notes Chapter III unity shader Foundation
![Cesiumjs 2022^ source code interpretation [8] - resource encapsulation and multithreading](/img/d2/99932660298b4a4cddd7e5e69faca1.png)
Cesiumjs 2022^ source code interpretation [8] - resource encapsulation and multithreading
随机推荐
Pair
be based on. NETCORE development blog project starblog - (14) realize theme switching function
What is regression testing? Talk about regression testing in the eyes of Ali Test Engineers
Function: store the strings entered in the main function in reverse order. For example, if you input the string "ABCDEFG", you should output "gfedcba".
C library function int fprintf (file *stream, const char *format,...) Send formatted output to stream
Network layer - routing
国元证券开户是真的安全可靠吗
Is the account opening of Guoyuan securities really safe and reliable
CesiumJS 2022^ 源码解读[8] - 资源封装与多线程
中电资讯-信贷业务数字化转型如何从星空到指尖?
GUI application: socket network chat room
Decompile and modify the non source exe or DLL with dnspy
UTS | causal reasoning random intervention based on Reinforcement Learning
In the process of seeking human intelligent AI, meta bet on self supervised learning
8. Go implementation of string conversion integer (ATOI) and leetcode
[common error] custom IP instantiation error
What is the future of software testing industry? Listen to the test veterans' answers
求esp32C3板子连接mssql方法
Technical practice online fault analysis and solutions (Part 1)
Five high-frequency questions were selected from the 200 questions raised by 3000 test engineers