脚本函数基础

19 篇文章 0 订阅

shell脚本编程系列


函数是一个脚本代码块,可以为其命名并在脚本中的任何位置重用它。每当需要在脚本中使用该代码块时,直接写函数名即可。称作调用函数。

创建函数
  • 方式1:
function name {
    commands
}

name定义了该函数的唯一名称,脚本中的函数名不能重复。

  • 方式二:
name(){
  commands
}

函数名后的空括号表明正在定义的是一个函数。

使用函数
#!/bin/bash
# using a function in a script

function func1 {
   echo "This is an example of a function"
}

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"

在这里插入图片描述
函数定义不一定非要放在shell脚本的开始部分,但是试图在定义之前调用它,会报错Command not found。
函数名必须是唯一的,如果定义了同名函数,那么新定义就会覆盖原先的定义。

#!/bin/bash
# testing using a duplicate function name

function func1 {
echo "This is the 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把函数视为一个小型脚本,运行结束时会返回一个退出状态码。
在默认情况下,函数的退出状态码是函数中最后一个命令返回的退出状态码。函数执行结束后,可以使用表准变量$?来确定函数的退出状态码。

#!/bin/bash
# testing the exit status of a function

func1() {
   echo "trying to display a non-existent file"
   ls -l badfile
}

echo "testing the function: "
func1
echo "The exit status is: $?"

在这里插入图片描述
使用函数的默认退出状态码是一个危险的事情。函数最后一个命令决定了退出状态码,即便前面的命令失败了,函数的退出状态码也可能为0.

#!/bin/bash
# testing the exit status of a function

func1() {
   ls -l badfile
   echo "This was a test of a bad command"
}

echo "testing the function:"
func1
echo "The exit status is: $?"

在这里插入图片描述

使用return命令

bash shell会使用return命令以特定的退出状态码退出函数,return命令允许指定一个整数值作为函数的退出状态码,从而提供一种简单的编程设定方式。要注意,退出状态码最大为255的整数,超过了这个值会发生溢出。

#!/bin/bash
# using the return command in a function

function dbl {
   read -p "Enter a value: " value
   echo "doubling the value"
   return $[ $value * 2 ]
}

dbl
echo "The new value is $?"

函数的输出可以保存到shell变量当中,比如result=$(dbl)

#!/bin/bash
# using the echo to return a value

function dbl {
   read -p "Enter a value: " value
   echo $[ $value * 2 ]
}

result=$(dbl)
echo "The new value is $result"

在这里插入图片描述
上面函数使用标准的echo语句返回值。除此之外,还可以通过反引号来获取输出的数据。

#!/bin/bash
# using recursion

function factorial {
   if [ $1 -eq 1 ]
   then
      echo 1
   else
      local temp=$[ $1 - 1 ]
      local result=$(factorial $temp)
      echo $[ $result * $1 ]
   fi
}

read -p "Enter value: " value
result=$(factorial $value)
echo "The factorial of $value is: $result"

在上面的递归调用时,通过$(factorial $temp)调用factorial函数,也就是自己。实现了阶乘的算法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lang20150928

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值