函数可以简化程序的代码量,达到更好的代码复用度,因此会让程序变得更加易读、简洁和易修改。其作用就是将需要多次使用的代码整合到一块,使其成为一个整体,然后通过函数名即可完成调用。

基本语法

function functionName () {
语句
return n
}

其他简化写法如下

function functionName {
语句
return n
}

functionName () {
语句
return n
}

建议采用非简化的书写方式,方便阅读代码

函数执行

  • 1、执行不带参数的函数,直接输入函数名即可,不需要带括号,如下所示:
functionName
  • 执行函数时,函数名前的关键字function和函数名后面的()均不需要带
  • 函数的定义必须要在执行的程序前定义或加载
  • 2、带参数的函数执行语法如下所示:
functionName arg1 arg2
> - Shell中的位置参数($1/$2.../$#/$?/$@)均可以做为函数的参数进行传递
> - $0比较特殊,仍然是父脚本的名称
> - 此时父脚本的参数会临时被函数的参数所掩盖或隐藏
> - 函数的参数变量是在函数体内里面进行定义

函数的执行总结如下:

  • 1、Shell各种程序的执行顺序为:系统别名->函数->系统命令->可执行文件等
  • 2、函数执行时,会和调用它的脚本共享变量,也可以为函数设定局部变量及特殊位置参数
  • 3、在Shell函数里面,return和exit功能类似,区别是return是退出函数,exit则是退出脚本
  • 4、return语句会返回一个值给调用函数的程序,exit则会返回一个值给执行当前脚本的Shell
  • 5、如果将函数单独存放为一个文件,在加载时需要使用source或 . 进行加载
  • 6、在函数内部一般使用local定义局部变量,仅在函数体内有效

函数示例

1、示例1:调用函数

[root@localhost Test]# cat testfunction.sh
#!/bin/bash # first function
function HelloWorld() {
echo "Hello world"
}
# second function
Welcome() {
echo "Welcome to Shanghai"
}
# third function
function HelloShell {
echo "Hello Shell"
}
# invoke functions
HelloWorld # 调用函数
Welcome
HelloShell
[root@localhost Test]# bash testfunction.sh
Hello world
Welcome to Shanghai
Hello Shell

2、示例2:从文件中调用函数

[root@localhost Test]# cat invokefunction.sh
function Sum () {
for((i=1;i<=100;i++))
do
((sum=sum+i))
done
echo '{1..100} sum is :' $sum
}
[root@localhost Test]# cat invokefunctionfromfile.sh
#!/bin/bash
path="/root/Test/invokefunction.sh"
if [ -f ${path} ]
then
source $path # 加载函数
Sum # 调用函数
else
echo "file not exist or error"
fi
[root@localhost Test]# bash invokefunctionfromfile.sh
{1..100} sum is : 5050

3、示例3:函数参数传递

[root@localhost Test]# cat functionwithargs.sh
#!/bin/bash
function Add () { # 定义函数
((sum=$1+$2))
echo "$1 + $2 sum is" ${sum}
}
Add $1 $2 # 调用函数并传递参数 [root@localhost Test]# bash functionwithargs.sh 100 150
100 + 150 sum is 250
[root@localhost Test]# bash functionwithargs.sh 509 150
509 + 150 sum is 659

4、示例4:使用return返回函数运行结果

[root@localhost Test]# cat functionwithreturn.sh
#!/bin/bash
function TestReturn() {
if [ -d $1 ]
then
return "122"
else
return "222"
fi
} TestReturn $1
result=$? # 获取函数返回值
if [ ${result} == "122" ]
then
echo "$1 exist ,return value is:" ${result}
else
echo "$1 not exist ,return value is:" ${result}
fi [root@localhost Test]# bash functionwithreturn.sh /etc/sysconfiggg
/etc/sysconfiggg not exist ,return value is: 222
[root@localhost Test]# bash functionwithreturn.sh /etc/sysconfig
/etc/sysconfig exist ,return value is: 122

在该示例中,主要通过$?获取返回值,但返回值的范围只能是0~255

5、示例5:使用echo返回函数运行结果

[root@localhost Test]# cat functionwithecho.sh
#!/bin/bash
function TestReturn() {
if [ -d $1 ]
then
echo "122"
else
echo "222"
fi
} result=$(TestReturn $1) # 获取函数返回值
if [ ${result} == "122" ]
then
echo "$1 exist ,return value is:" ${result}
else
echo "$1 not exist ,return value is:" ${result}
fi [root@localhost Test]# bash functionwithecho.sh /etc/sysconfig
/etc/sysconfig exist ,return value is: 122
[root@localhost Test]# bash functionwithecho.sh /etc/sysconfiggg
/etc/sysconfiggg not exist ,return value is: 222

在该示例中,主要使用$()获取返回值,在该方法中,没有范围限制,是一种比较安全的返回方式。

[root@localhost Test]# cat functionwithecho.sh
#!/bin/bash
function TestReturn() {
if [ -d $1 ]
then
echo "$1 exist"
else
echo "$1 not exist"
fi
} result=$(TestReturn $1) # 获取返回值,返回的结果是字符串
if [ "${result}" == "$1 exist" ]
then
echo "$1 exist ,return value is:" ${result}
else
echo "$1 not exist ,return value is:" ${result}
fi [root@localhost Test]# bash functionwithecho.sh /etc/sysconfiggg
/etc/sysconfiggg not exist ,return value is: /etc/sysconfiggg not exist
[root@localhost Test]# bash functionwithecho.sh /etc/sysconfig
/etc/sysconfig exist ,return value is: /etc/sysconfig exist

本文同步在微信订阅号上发布,如各位小伙伴们喜欢我的文章,也可以关注我的微信订阅号:woaitest,或扫描下面的二维码添加关注:

Shell编程-09-Shell中的函数的更多相关文章

  1. shell编程系列6--shell中的函数

    shell编程系列6--shell中的函数 .函数介绍 linux shell中的函数和大多数编程语言中的函数一样 将相似的任务或者代码封装到函数中,供其他地方调用 语法格式 第一种格式 name() ...

  2. shell编程系列7--shell中常用的工具find、locate、which、whereis

    shell编程系列7--shell中常用的工具find.locate.which.whereis .文件查找之find命令 语法格式:find [路径] [选项] [操作] 选项 -name 根据文件 ...

  3. 【Shell编程】Shell程序设计

    1.Shell简介   作为Linux灵感来源的Unix系统最初是没有图形化界面的,所有的任务都是通过命令行来实现的.因此,Unix的命令行系统得到了很大的发展,逐步成为一个功能强大的系统.   Sh ...

  4. Linux shell编程02 shell程序的执行 及文件权限

    第一个shell脚本 1.       shell编程的方式 交互式shell编程 非交互式shell编程:执行的语句存放到一个文件 shell脚本:可以任意文件名,建议扩展名为sh 2.       ...

  5. 【Shell编程】Shell基本语法

    Shell 语法   Shell程序设计作为一种脚本语言,在Linux系统中有广泛的应用,本文记录了关于Shell程序设计的基础语法知识和常用命令,方便查询,熟练使用shell也需要经常实践,这对于完 ...

  6. Shell编程(二)——shell的基础知识及常用命令

    shell的基础知识 一.bash有以下特点: 1.记录命令历史 2.指令和文件名补全 3.别名 alias rm='rm -i' 4.通配符 * 0个或多个字符 ?​匹配一个字符 5 输入输出重定向 ...

  7. shell编程01—shell基础

    01.学习shell编程需要的知识储备 1.vi.vim编辑器的命令,vimrc设置 2.命令基础,100多个命令 3.基础.高端的网络服务,nfs,rsync,inotify,lanmp,sersy ...

  8. Linux - 简明Shell编程09 - 重定向(Redirection)

    脚本地址 https://github.com/anliven/L-Shell/tree/master/Shell-Basics 示例脚本及注释 #!/bin/bash pwd > 1.log ...

  9. linux下的Shell编程(8)自定义函数

    Shell Script中也可以使用自定义的函数,其语法形式如下: functionname() { - }

  10. 【shell编程】之基础知识-函数

    linux shell 可以用户定义函数,然后在shell脚本中可以随便调用. shell中函数的定义格式如下: [ function ] funname [()] { action; [return ...

随机推荐

  1. javascript DOM基础操作

    DOM(Document Object Model)即文档对象模型,针对HTML和XML文档的API(应用程序接口).DOM描绘了一个层次化的节点树,运行开发人员添加.移除和修改页面的某一部分.DOM ...

  2. nginx 的 负载均衡

    一.正向代理和反向代理 1.正向代理 正向代理类似一个跳板机,代理访问外部资源. 正向代理是客户端和目标服务器之间的代理服务器(中间服务器).为了从指定的服务器取得内容,客户端向代理服务器发送一个请求 ...

  3. node.js 进程崩溃处理

    process.on('uncaughtException', (err) => { console.error('有错误'); });

  4. tiny cc 编译器,tinycc,变种

    去掉了 -run 参数 下载代码和编译好的程序

  5. Eclipse快捷键系列

    查看Eclipse自定义的快捷键或者自己定义快捷键的方式 Window --> preference --> general --> Keys 在光标所在行之后插入一行,省去了将光标 ...

  6. 数据库MySQL 之 索引原理与慢查询优化

    数据库MySQL 之 索引原理与慢查询优化 浏览目录 索引介绍方法类型 聚合索引辅助索引 测试索引 正确使用索引 组合索引 注意事项 查询计划 慢查询日志 大数据量分页优化 一.索引介绍方法类型 1. ...

  7. Mockplus3.5.0.1新增标注功能

    Mockplus3.5.0.1版本中,新增了标注功能.多种标注模式,智能生成,随时查看.原型设计效率更高. Mockplus的标注功能有以下四种模式: 1.无选中标注 在未选中任何组件时,按住Ctrl ...

  8. How to Create Triggers in MySQL

    https://www.sitepoint.com/how-to-create-mysql-triggers/ I created two tables: CREATE TABLE `sw_user` ...

  9. centos6.5上配置apache + mysql + php4.4.9 + eaccelerator-0.9.5 + postgresql-8.3.13 备忘

    1.apache + mysql 直接利用 yum 安装 yum -y install httpd httpd-devel mysql mysql-server httpd-manual mod_pe ...

  10. 纯H5+c3实现表单验证

    客户端验证是网页客户端程序最常用的功能之一,我们之前使用了各种各样的js库来进行表单的验证.HTML5其实早已为我们提供了表单验证的功能.至于为啥没有流行起来估计是兼容性的问题还有就是样式太丑陋了吧. ...