【Linux】【Shell】Shell 函数

研究学习 Linux Shell 的系列文章.

这篇文章主要讲 Shell 编程中的条件判断与流程控制.

1. Shell 函数的定义和调用

Shell 函数定义的语法格式:

[ function ] funname [()]
{
    函数体;

    [return int;]
}
  • 关键字 function() 可省略.
  • 参数返回,可以显示加:return 返回;如果不加,将以最后一条命令运行结果,作为返回值. return 后跟数值 n (0-255).

 
Shell 函数调用时仅使用函数名,不带 (),例如 eg1.sh:

#!/bin/bash

myFunc(){
    echo "My first shell function."
}

echo "calling myFunc()"
myFunc
[root@cloudvm ~]# ./eg1.sh 
calling myFunc()
My first shell function.
[root@cloudvm ~]# echo $?
0

 
使用 return 语句,例如 eg2.sh:

#!/bin/bash

myAdd(){
    echo "adding two numbers"
    read -t 30 -p "Please input 1st num: " num1
    read -t 30 -p "Please input 2nd num: " num2
    return $(($num1+$num2))
}

myAdd
echo "The sum is $?."
[root@cloudvm ~]# ./eg2.sh 
adding two numbers
Please input 1st num: 1
Please input 2nd num: 3
The sum is 4.

2. Shell 函数传递参数

调用 Shell 函数时相当于使用 Shell 命令,仅使用函数名,不带 (). 传递参数使用位置参数变量. 例如 eg3.sh:

#!/bin/bash

myFuncParam(){
    echo "The 1st param is $1."
    echo "The 2nd param is $2."
    echo "The 3rd param is $3."
    echo "..."
    echo "The 10th param is ${10}."
    echo "The 11th param is ${11}."
    echo ""
    echo "The total number of parameters is $#."
    echo "The total parameters are $*."
    echo "The total parameters are $@."
}

myFuncParam 11 12 13 14 15 16 17 18 19 50 51 52
[root@cloudvm ~]# ./eg3.sh 
The 1st param is 11.
The 2nd param is 12.
The 3rd param is 13.
...
The 10th param is 50.
The 11th param is 51.

The total number of parameters is 12.
The total parameters are 11 12 13 14 15 16 17 18 19 50 51 52.
The total parameters are 11 12 13 14 15 16 17 18 19 50 51 52.

3. Shell 文件包含

使用 source 命令可以包含外部脚本

. filename   # 注意点号(.)和文件名中间有一空格

source filename

eg4.sh 中包含 eg1.sh

#!/bin/bash

source ./eg1.sh
[root@cloudvm ~]# ./eg4.sh 
calling myFunc()
My first shell function.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值