当前位置:网站首页>Shell Function
Shell Function
2022-07-02 01:04:00 【Hadron's blog】
One , Definition of function ( Two ways )
1.
function Function name {
command
} // This is a standard way of writing
2.
Function name (){ // Most commonly used because of the most concise
command
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
After the function is defined, it will not execute automatically , You need to call , The advantage is that you can write a piece of function code as a function , If you need to call the definition directly, it doesn't matter even if there are syntax errors , If you don't call, you won't report an error. Of course, the ultimate purpose of writing functions is to call , In order to implement a function block
Two , Function return value :
return Represents the exit function and returns an exit value , You can use $? The variable displays the value
Usage principle :
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, If the value exceeds the value, it will be the remainder 256
example
444 % 256
1) 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 to print "this is a function!
}
fun1 // Writing the function name directly will run the code in the function body
[[email protected] myscripts]# . fun.sh
this is a function!
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
Be careful ①: 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 !
#!/bin/bash
f1 (){
echo hello
}
f1 (){
echo world
}
f1
[[email protected] ~]# . f1.sh
world
Be careful ②: The function must be defined before calling !
#!/bin/bash
f1 (){
echo hello
}
f3 (){
echo "$(f1) $(f2)"
}
f2 (){
echo world
}
f3
Be careful ③: You don't have to define the function at the beginning of the script , As long as it is defined before the call
In case of nested calls in other places , You can't write the value of a function directly , Avoid being unable to recognize , You can use a reverse apostrophe , It is equivalent to the result of calling the function
#!/bin/bash
f1 (){
echo hello
}
f2 (){
echo world
}
f3 (){
echo "`f1` `f2`" // If it's directly f1 and f2 Words , It won't print out hello world And it will be f1 f2
}
f3
- 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.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
3、 ... and , Example
vim localrepo. sh
#!/bin/bash
function backuprepo {
cd /etc/yum.repo.d
mkdir repo.bak
mv * .repo repo.bak
mount /dev/sr0 /mnt > /dev/null
}
makelocalrepo() {
echo '[local]
name= local
baseurl=file: / , /mnt
enabled=1
gpgcheck=0' > local.repo
}
uselocal repo (){
yum clean all > /dev/null
yum makecache > /dev/null
yum install -y httpd > /dev/null
}
######main#######
backuprepo
makelocalrepo
uselocalrepo
- 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.
Four , Function arguments
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 two numbers is : $SUM”
}
sum
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
1. Function scope
stay Shell The execution of the function in the script does not open a new child Shell, But only in the currently defined Shell Effective in the environment . If Shell The variables in the script are not specially set , The default is valid throughout the script . When writing scripts , Sometimes you need to limit the value of a variable inside a function , You can use built-in commands local To achieve . Use of internal variables of functions , It can avoid the influence of variables with the same name inside and outside the function on the script results .
shell Variables in scripts are globally valid by default
local command : Restrict variables to functions and use
[[email protected] ~]# vim myfun.sh
myfun ()
{
local i
i=8
echo $i
}
i=9
myfun
echo $i
In the above script myfun The function uses local Command to set variables i, Its function is to change the variable i Inside the function .myfun Variables are also defined outside the function i, Internal variables i And global variables i They don't influence each other . When the script executes, the function... Is called first myfun, Function internal variables i by 8, So the output is 8. After calling the function , To the variable i The assignment is 9, Then print external variables i, So I output 9
myfunc() {
a=8
echo $a
}
myfunc
echo $a
#!/bin/bash
myfunc() {
a=8
echo $a
myfunc
a=9
echo $a I
- 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.
2. The ginseng
Arguments to functions
1) The parameters of the function
Calculate the location variable $1 and $2 And
#!/bin/bash
add (){
let sum=$1+$2 // The position variable here is the position variable of the function , So write it after the calling function , If it is used when calling a script, then Can't succeed
echo $sum
}
add 4 5
2) Script parameters
#!/bin/bash
add (){
let sum=$1+$2
echo $sum
}
add $1 $2 // This is equivalent to calling the parameters of the script , Then pass the location variable of the script to the function for calculation
Pass the parameters to the positional parameters in the function through the script $1
#!/bin/bash
fun1(){
rm -rf $1
}
fun1 $1
Pass parameters directly when calling a function
#!/bin/bash fun1(){
rm -rf $1
}
fun1 /root/a.txt
How to pass and use multiple parameters in functions
- 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.
3. 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
#!/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
Calculation 5 The factorial
# Factorial 5! 5*4*3*2*1
#!/bin/bash
fa () {
if [ $1 -eq 1 ]
then
echo 1
else
local tp=$[ $1 - 1]
local res=$(fa $tp)
echo $[ $1 * $res ]
fi
}
- 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.
5、 ... and , 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
[[email protected] ~]# a=nihao
#!/bin/bash // Write a function , Print first a Value , Then change a Reprint the value of
f1 (){
echo $a
a=world
echo $a
}
f1
[[email protected] ~]# source f1.sh // use source Execute the script , Will find a The value of
nihao
world
[[email protected] ~]# echo $a
world
Use... In the body of a function local Defining variables a Value
#!/bin/bash
f1 (){
echo $a
local a=world
echo $a
}
f1
[[email protected] ~]# source f1.sh // Execute script discovery a The value of
world
world
#!/bin/bash
f1 (){
echo $a
local a=world
echo $a
}
f1
echo $a
- 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.
边栏推荐
- Global and Chinese market of collaborative applications 2022-2028: Research Report on technology, participants, trends, market size and share
- How to extract login cookies when JMeter performs interface testing
- Bilstm CRF code implementation
- Synthetic watermelon game wechat applet source code / wechat game applet source code
- Deb file installation
- How to open an account for individual stock speculation? Is it safe?
- AIX存储管理之卷组属性的查看和修改(二)
- Creation of volume group for AIX storage management (I)
- Global and Chinese market of ancillary software 2022-2028: Research Report on technology, participants, trends, market size and share
- Promise and modular programming
猜你喜欢
Collection: comprehensive summary of storage knowledge
Source code of Qiwei automatic card issuing system
Entrepreneurship is a little risky. Read the data and do a business analysis
【底部弹出-选择器】uniapp Picker组件——底部弹起的滚动选择器
JS -- image to base code, base to file object
Upgraded wechat tool applet source code for mobile phone detection - supports a variety of main traffic modes
[eight sorting ③] quick sorting (dynamic graph deduction Hoare method, digging method, front and back pointer method)
2022 safety officer-a certificate examination questions and online simulation examination
excel查找与引用函数
To meet the needs of consumers in technological upgrading, Angel water purifier's competitive way of "value war"
随机推荐
Entrepreneurship is a little risky. Read the data and do a business analysis
Promise和模块块化编程
Global and Chinese market of safety detection systems 2022-2028: Research Report on technology, participants, trends, market size and share
[eight sorts ②] select sort (select sort, heap sort)
JMeter做接口测试,如何提取登录Cookie
cookie、session、tooken
JS common library CDN recommendation
Global and Chinese markets for distributed generation and energy storage in telecommunications networks 2022-2028: Research Report on technology, participants, trends, market size and share
Bubble Sort Graph
Global and Chinese markets for freight and logistics 2022-2028: Research Report on technology, participants, trends, market size and share
How do Lenovo computers connect Bluetooth headsets?
Node -- egg implements the interface of uploading files
Otaku wallpaper Daquan wechat applet source code - with dynamic wallpaper to support a variety of traffic owners
【会议资源】2022年第三届自动化科学与工程国际会议(JCASE 2022)
449 original code, complement code, inverse code
Global and Chinese markets for the application of artificial intelligence in security, public security and national security 2022-2028: Research Report on technology, participants, trends, market size
Output results of convolution operation with multiple tensors and multiple convolution kernels
Kuberntes cloud native combat high availability deployment architecture
[wechat authorized login] the small program developed by uniapp realizes the function of obtaining wechat authorized login
Leetcode skimming: stack and queue 05 (inverse Polish expression evaluation)