---
title: "Shell学习（6）函数"
author: "zenoh"
date: "2011-06-03T15:08:04Z"
tags: []
categories: ["操作系统"]
slug: "shell-6"
draft: false
lastmod: "2011-06-03T15:16:56Z"
id: 1069576
url: "https://zenoh.iteye.com/blog/1069576"
---

函数

 

 

 

Bash调用函数不会开启新的子shell，会在现有的shell环境中执行该函数。

函数的语法形式：

 

 调用：函数名 参数1 参数2 ....

FUNCNAME变量，值的内容是函数名

取消函数定义：unset -f 函数名

return指令  $?传回值

作用范围：函数仅在定义的shell环境中有效，如果要传递函数给子shell环境使用，可使用内置命令export和-f选项：export -f 函数名  
如果没有特别设定变量的属性，那么在script中自定义的变量称为全局变量，作用范围在整个script文件中  
内置命令local，设定变量属性为私有  
主程序中，尽量不要用传入函数的全局变量的值来控制函数执行后的程序流程

位置参数  
含义

![](http://pic002.cnblogs.com/images/2011/128696/2011031420201757.jpg)

移动位置参数：shift n  
指定位置参数：set命令

例子：

```
#!/bin/bash
declare -i i=0
set 61 62 63 64 65 66 67 68 69 70
for p in $@
do
	((i++))
	echo "第 $i 个位置参数 \$$i=$p"
done
```

  

 

 

运用位置参数传递参数值给函数时，原有的位置参数会被保存，其内含值不会受到影响  
取用命令行的选项和参数：

getopts 选项行 选项变量

选项行由各选项的单一字符组成，getopts由命令行取得选项，把它放入选项变量中，如果该选项需要额外的参数，参数值会放入OPTARG变量中  
例子:

```
#!/bin/bash
while getopts u:ah opt
do
	case $opt in
	u)
	echo "提供了选项u和参数：$OPTARG";;
	a)
	echo "提供了选项a";;
	h)
	echo "提供了选项h";;
	*)
	;;
	esac
done
```

 

 

 ![](http://pic002.cnblogs.com/images/2011/128696/2011031420492943.png)

 

建立函数库  
[例子见后页](/admin/blogs/1067629 "建立函数库")

递归函数﻿

例子:

```
#!/bin/bash
function factor_in () {
	local tmp
	local tmp1
	
	tmp="$1"
	if [ $tmp -eq 1 ] ; then
		echo -n " 1 "
		r=1
	else
		echo -n " $tmp * "
		tmp1=$tmp
		tmp=$(($tmp-1))
		factor_in $tmp
		r=$(($tmp*$r))
	fi
}
if [ $# -ne 1 ] ;then
	echo "使用方法：$0 正整数"
	exit 1
fi
echo
echo -n $1"! = "
factor_in $1
echo -n "= $r"
echo
```

 

 

 

 ![](http://pic002.cnblogs.com/images/2011/128696/2011031420591797.png)

```
function 函数名称()
{
	命令区域
}

函数名称()
{
	命令区域
}

function 函数名称
{
	命令区域
}
```