Shell function and its scope and parameter passing, recursion and creation of function library (easy! The recursive way is simple!)

Shell function and its scope and parameter passing, recursion and creating function library

One, Shell function

When writing shell scripts, you often find that the same piece of code is used in multiple places. If it's just a small piece of code, it generally doesn't matter. But it is too tiring to rewrite large blocks of code multiple times in a shell script. The user-defined function provided by the bash shell can solve this problem. The shell script code can be encapsulated in a function so that it can be used multiple times anywhere in the script.

  • Call functions

A function is a script code block, you can name it and reuse it anywhere in the code. When you want to use the code block in a script, just use the name of the function.

Two, create a function

1.Shell function format

第一种格式:

function 函数名 {
命令序列
}

第二种格式:

函数名() {
命令序列
}

2. The return value of the function

return means to exit the function and return an exit value, which can be displayed by the $? variable in the script

Usage principles:
1) 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.
2) The exit status code must be 0~255, and the value will be divided by 256 if it exceeds

Example 1:

[root@localhost ~]#vim hs1.sh
[root@localhost ~]#chmod +x hs1.sh #赋予执行权限
[root@localhost ~]#cat hs1.sh #查看脚本内容
#!/bin/bash
function db1 {          #db1是函数名
   read -p "请输入:" value  #value是变量名
   return $[$value * 2]    #直接用value乘以2的值作为返回值
}
#####main#####
db1                       #调用函数db1
echo $?                   #输出上个命令的执行结果返回值
[root@localhost ~]#sh -vx hs1.sh #-v:执行脚本前输出脚本内容;-x:列出执行过程
#!/bin/bash
function db1 {
   read -p "请输入:" value
   return $[$value * 2]
}
db1
+ db1
+ read -p $'\350\257\267\350\276\223\345\205\245\357\274\232' value
请输入:3
+ return 6
echo $?
+ echo 6
6

Example 2:

[root@localhost ~]#vim hs2.sh
[root@localhost ~]#cat hs2.sh #查看脚本内容
#!/bin/bash
db1() {                  #db1是函数名
read -p "请输入:" value   #value是变量
echo $[$value * 2]      #直接输出2乘value的结果
}
result=`db1`            #把函数得出的值直接赋给变量result
echo $result            #输出result的值
[root@localhost ~]#sh -n hs2.sh #查看脚本有无语法错误
[root@localhost ~]#sh -x hs2.sh #查看脚本执行过程
++ db1
++ read -p $'\350\257\267\350\276\223\345\205\245\357\274\232' value
请输入:10
++ echo 20
+ result=20
+ echo 20
20
[root@localhost ~]#chmod +x hs2.sh #赋给脚本执行权限
[root@localhost ~]#./hs2.sh #执行脚本
请输入:10
20

Three, transfer parameters

The bash shell treats functions as small scripts, which means that it can pass parameters to functions like normal scripts. Functions can use standard parameter environment variables to represent the parameters uploaded to the function from the command line. For example, the function name will be defined in the $0 variable, and any parameters on the function command line will be defined by $1, 2, etc. It can also be defined by special variables 2 etc. Special variables are also available2 and other fixed meaning . Can also be used Laid special variable amount # determines the number of arguments passed to the function.

[root@localhost ~]#vim hschuancan.sh
[root@localhost ~]#cat hschuancan.sh #查看脚本内容
#!/bin/bash
sum () {               #函数名为sum
su=$[$1 + $2]         #$1和$2求和以后的值赋给变量su
echo $su              #输出变量su的值
}
#########main##########
sum $1 $2             #这段是主代码,调用函数sum,sum函数名后跟着两个参数$1、$2
[root@localhost ~]#chmod +x hschuancan.sh #赋予执行权限
[root@localhost ~]#sh -n hschuancan.sh  #查是否有语法错误
[root@localhost ~]#./hschuancan.sh 8 9 #脚本后跟两个参数$1是8,$2是9
17                #执行结果是17

When the script is executed, the following two parameters are passed to the main code in the script, which is the two parameters followed by sum, and then when the function is executed, the function then references the two parameters following the main code sum, namely $1 and $2

Note: This script executes the main sum $1 $2 first, and then executes the function sum() defined above

Fourth, the scope of function variables

  • Functions in Shell scripts are only valid in the current Shell environment
  • Variables in Shell scripts are globally effective by default
  • Use the local command to limit the variable to the function
[root@localhost ~]#sh -vx hs3.sh 
#!/bin/bash
abc () {
echo "函数内部第一个i的值:$i"
i=$[$i+1]
echo "函数内部第二个i的值:$i"
local i       #设置局部变量
i=8
echo "内部第三个i的值:$i"
}
######main######
i=9             #全局环境
+ i=9
abc             
+ abc
+ echo $'\345\207\275\346\225\260\345\206\205\351\203\250\347\254\254\344\270\200\344\270\252i\347\232\204\345\200\274\357\274\2329'
函数内部第一个i的值:9  #先i=9作为全局变量的时候调用函数abc,所以这里的i依然是全局变量
+ i=10  #这里i=$[$i+1],依然是全局变量
+ echo $'\345\207\275\346\225\260\345\206\205\351\203\250\347\254\254\344\272\214\344\270\252i\347\232\204\345\200\274\357\274\23210'
函数内部第二个i的值:10 #还没设置局部变量,这是刚刚运算得出的值
+ local i #设置局部变量
+ i=8  #局部变量值为8,不影响外部的全局变量
+ echo $'\345\206\205\351\203\250\347\254\254\344\270\211\344\270\252i\347\232\204\345\200\274\357\274\2328'
内部第三个i的值:8 #局部变量值为8
echo "函数外部i的值:$i"
+ echo $'\345\207\275\346\225\260\345\244\226\351\203\250i\347\232\204\345\200\274\357\274\23210'
函数外部i的值:10  #外部全局变量调用函数以后它的值加1
[root@localhost ~]#cat hs3.sh 
#!/bin/bash
abc () {
echo "函数内部第一个i的值:$i"
i=$[$i+1]
echo "函数内部第二个i的值:$i"
local i       #设置局部变量
i=8
echo "内部第三个i的值:$i"
}
######main######
i=9             #全局环境
abc             
echo "函数外部i的值:$i"

Note: Local and global are two kinds of variables, which can be assigned different values, but they can have the same name

Five, recursive factorial

A function can call itself to get the result, and usually a recursive function has a baseline value that it can eventually iterate to. The classic example of a recursive algorithm is to calculate the factorial. The factorial of a number is the value of multiplying all the numbers before that number by the number, such as the factorial of 5:

5! = 5 * 4 * 3 * 2 * 1

Using recursion can be simplified to the following form:

x! = x * (x-1)!

After understanding the principle, it is relatively simple to do, so it is written in a script:

Take the factorial of 3 as an example

[root@localhost ~]#vim jc.sh 
[root@localhost ~]#cat jc.sh 
fact ()  {
  if [ $1 -eq 1 ] #等于1的时候输出1,不等于的时候进入else
  then 
    echo 1
  else  #下面定义两个局部变量,只在当前函数内部有效
  local temp=$[$1 - 1]
  local result=$(fact $temp)
    echo $[$1 * $result] #当n=3,也就相当于(3*result(2*result(1)))
  fi
}
read -p "请输入:" n
result=$(fact $n)
echo $result
[root@localhost ~]#sh -x jc.sh 
+ read -p $'\350\257\267\350\276\223\345\205\245\357\274\232' n
请输入:3
++ fact 3
++ '[' 3 -eq 1 ']'
++ local temp=2
+++ fact 2
+++ '[' 2 -eq 1 ']'
+++ local temp=1
++++ fact 1
++++ '[' 1 -eq 1 ']'
++++ echo 1
+++ local result=1
+++ echo 2
++ local result=2
++ echo 6
+ result=6
+ echo 6
6

Six, recursive directory

[root@localhost ~]#vim dgml.sh
[root@localhost ~]#cat dgml.sh 
#!/bin/bash
function list_files () {
for f in `ls $1` 
do
if [ -d "$1/$f" ]
 then
    echo "$2$f"     #如果是目录就输出这个目录,$2为空格是用于区分父子目录
list_files "$1/$f" "  $2"  #如果想区分的明显点,可在$2前面加空格     
else
    echo "$2$f"               #不是目录则输出$f结果
fi
done
}

list_files "/var/log" ""
[root@localhost ~]#./dgml.sh  #执行脚本,目录和子目录分明
anaconda
  anaconda.log
  ifcfg.log
  journal.log
  ks-script-1Pn8cs.log
  ks-script-W4EI_q.log
  packaging.log
  program.log
  storage.log
  syslog
  X.log
audit
  audit.log

Seven, create a library

[root@localhost ~]#cat hsku.sh 
#!/bin/bash

jiafa () {
echo $[$1 + $2]
}

chengfa () {
echo $[$1 * $2]
}

chufa () {
if [ $2 -ne 0 ];then
    echo $[$1 / $2]
else
    echo "$2不能为0"
fi
}


[root@localhost ~]#cat fuzhi.sh 
#!/bin/bash
. hsku.sh
value1=10
value2=5

result1=`jiafa $value1 $value2`
result2=`chengfa $value1 $value2`
result3=`chufa $value1 $value2`

echo "加法结果为: $result1"
echo "乘法结果为: $result2"
echo "除法结果为: $result3"
[root@localhost ~]#./fuzhi.sh 
加法结果为: 15
乘法结果为: 50
除法结果为: 2

Guess you like

Origin blog.csdn.net/qq_35456705/article/details/111878641