研究学习 Linux Shell 的系列文章.
这篇文章主要讲 Shell 编程中的条件判断与流程控制.
文章目录
- 1. Shell 函数的定义和调用
- 2. Shell 函数传递参数
- 3. Shell 文件包含
1. Shell 函数的定义和调用
Shell 函数定义的语法格式:
复制代码
1
2
3
4
5
6
7[ function ] funname [()] { 函数体; [return int;] }
- 关键字
function
和()
可省略. - 参数返回,可以显示加:return 返回;如果不加,将以最后一条命令运行结果,作为返回值. return 后跟数值 n (0-255).
Shell 函数调用时仅使用函数名
,不带 ()
,例如 eg1.sh
:
复制代码
1
2
3
4
5
6
7
8
9#!/bin/bash myFunc(){ echo "My first shell function." } echo "calling myFunc()" myFunc
复制代码
1
2
3
4
5
6[root@cloudvm ~]# ./eg1.sh calling myFunc() My first shell function. [root@cloudvm ~]# echo $? 0
使用 return 语句,例如 eg2.sh
:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12#!/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 $?."
复制代码
1
2
3
4
5
6[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
:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17#!/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
复制代码
1
2
3
4
5
6
7
8
9
10
11
12[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
命令可以包含外部脚本
复制代码
1
2. filename # 注意点号(.)和文件名中间有一空格
或
复制代码
1
2source filename
在 eg4.sh
中包含 eg1.sh
:
复制代码
1
2
3
4#!/bin/bash source ./eg1.sh
复制代码
1
2
3
4[root@cloudvm ~]# ./eg4.sh calling myFunc() My first shell function.
最后
以上就是发嗲星星最近收集整理的关于【Linux】【Shell】Shell 函数的全部内容,更多相关【Linux】【Shell】Shell内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复