在shell脚本编写中,通常有很多处使用相同的代码。如果这些代码比较短小,name通常并不费事。但是,如果有打断代码需要重写,则会让人厌烦,这个我们就需要使用函数来处理;
函数是被富裕名称的脚本代码块,可以在代码的任意位置重复使用。引用函数的过程,我们称之为调用;
在bash shell脚本中创建函数可以使用两种格式:
function name { #name为唯一名称 commands #commands为组成函数功能的命令 }
另外一种格式
name() {
commands
}
相应的函数名需要在脚本中指定
#!/bin/bash # using a function in a script function func1 { echo "This is an example of a funcation" } count=1 while [ $count -le 5 ] do func1 count=$[ $count + 1 ] done echo "This is the end of the loop" func1 echo "Now this is the end of the script"
注意,不能在函数被定义之前去调用这个函数,会报错
#!/bin/bash # using a function located in the middle of a script count=1 echo "This line comes before the function definition" function func1 { echo "This is an example of a function" } while [ $count -le 5 ] do func1 count=$[ $count + 1 ] done echo "This is the end of the loop" func2 #没有定义func2,所以这里会报错 echo "Now this is the end of the script"
函数的命名也需要注意,必须唯一。如果重新定义了函数,则新定义的函数就会覆盖原来的函数
#!/bin/bash # testing using a duplicate function name function func1 { echo "This is first definition of the function name" } func1 function func1 { #新定义的函数就会覆盖原来的函数 echo "This is a repeat of the same function name" } func1 echo "This is the end of the script"
bash shell将函数看成小型的脚本,并以退出转态结束。函数退出转态有三种生成方式;
原文:https://www.cnblogs.com/BurnovBlog/p/10799057.html