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

基本语法

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. VS新建API控制器时提示“运行所选代码生成器时出错”

    使用Nuget安装microsoft.entityframeworkcore.tools这个包就行了,安装时注意版本. 根据下图提示应该是新建控制器时用到了这个包,所以安装一下就好了.之前遇到过一次, ...

  2. Attribute Syntax

    Attribute Syntax This section describes the syntax with which __attribute__ may be used, and the con ...

  3. swoole的EventLoop学习

    我们先使用php来写一个socket的服务端.先从最开始的模型开始将起逐步引申到为何要使用eventloop 1.最简单的socket服务端,直接按照官方文档来执行 <?php $sock = ...

  4. CButtonST|CUniButton等按钮类的使用

    CButtonST CButtonST类的使用参考链接:http://www.cnblogs.com/lidabo/archive/2012/12/17/2821122.html CCeButtonS ...

  5. Java Http协议处理类

    public class HttpRequest { public static String doGet(String url,String params) throws Exception{ re ...

  6. Spring ApplicationContext(二)环境准备

    Spring ApplicationContext(二)环境准备 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) 本节介绍 ...

  7. Servlet 3.0 规范(二)注解驱动和异步请求

    Servlet 3.0 规范(二)注解驱动和异步请求 在 Servlet 3.0 时支持注解启动,不再需要 web.xml 配制文件. 一.Servlet 3.0 组件 Servlet 容器的组件大致 ...

  8. SpringMVC学习笔记:数据的接收与返回

    SpringMVC的定义:Spring Web MVC is the original web framework built on the Servlet API and included in t ...

  9. 【算法专题】工欲善其事必先利其器—— 常用函数和STL

    一.    常用函数 #include <stdio.h> int getchar( void );               //读取一个字符, 一般用来去掉无用字符 char *ge ...

  10. python学习 day12 (3月18日)----(装饰器内置函数)

    读时间函数: # import time # def func(): # start_time = time.time() # 代码运行之前的时间 # print('这是一个func函数') # ti ...