当前位置:网站首页>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.
边栏推荐
- AI helps make new breakthroughs in art design plagiarism retrieval! Professor Liu Fang's team paper was employed by ACM mm, a multimedia top-level conference
- 国元证券开户是真的安全可靠吗
- Arc 135 supplementary report
- Delete all elements with a value of Y. The values of array elements and y are entered by the main function through the keyboard.
- On the day when 28K joined Huawei testing post, I cried: everything I have done in these five months is worth it
- Function: store the strings entered in the main function in reverse order. For example, if you input the string "ABCDEFG", you should output "gfedcba".
- Future源码一观-JUC系列
- Unity Shader入门精要读书笔记 第三章 Unity Shader基础
- It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction
- Pytest unit test framework: simple and easy to use parameterization and multiple operation modes
猜你喜欢
Beijing invites reporters and media
Gauss elimination method and template code
How to use AHAS to ensure the stability of Web services?
Makefile judge custom variables
功能:求出菲波那契数列的前一项与后一项之比的极限的 近似值。例如:当误差为0.0001时,函数值为0.618056。
Bodong medical sprint Hong Kong stocks: a 9-month loss of 200million Hillhouse and Philips are shareholders
Cesiumjs 2022^ source code interpretation [8] - resource encapsulation and multithreading
中电资讯-信贷业务数字化转型如何从星空到指尖?
What is regression testing? Talk about regression testing in the eyes of Ali Test Engineers
Technical practice online fault analysis and solutions (Part 1)
随机推荐
基于.NetCore开发博客项目 StarBlog - (14) 实现主题切换功能
【.NET+MQTT】.NET6 环境下实现MQTT通信,以及服务端、客户端的双边消息订阅与发布的代码演示
Design of database table foreign key
Function: write function fun to find s=1^k+2^k +3^k ++ The value of n^k, (the cumulative sum of the K power of 1 to the K power of n).
UTS | causal reasoning random intervention based on Reinforcement Learning
Future source code view -juc series
Who moved my code!
The FISCO bcos console calls the contract and reports an error does not exist
8. Go implementation of string conversion integer (ATOI) and leetcode
Cesiumjs 2022^ source code interpretation [8] - resource encapsulation and multithreading
Att & CK actual combat series - red team actual combat - V
Future源码一观-JUC系列
Introduction to thread pool
The difference between fetchtype lazy and eagle in JPA
system. Exit (0) and system exit(1)
Day05 表格
@EnableAsync @Async
查询效率提升10倍!3种优化方案,帮你解决MySQL深分页问题
GUI 应用:socket 网络聊天室
基于.NetCore开发博客项目 StarBlog - (14) 实现主题切换功能