首页 > 系统 > Linux > 正文

Shell函数的7种用法介绍

2019-10-26 18:43:17
字体:
来源:转载
供稿:网友

1. 在shell文件内部定义函数并引用:

代码如下:
[~/shell/function]# cat factorial.sh
#!/bin/bash
function factorial
{
factorial=1
for (( i=1;i <= $1;i++ ))
        do
        factorial=$[ $factorial * $i ]
        done
echo $1的阶乘是:$factorial
}
echo '程序名':$0,用于求阶乘
factorial $1
[~/shell/function]# ./factorial.sh 10

程序名:./factorial.sh,用于求阶乘
10的阶乘是:3628800

2.返回值

函数返回码是指函数最后一条命令的状态码,可以用于函数返回值
使用return命令手动指定返回值:

代码如下:
[~/shell/function]# cat return.sh
#!/bin/bash
function fun1 {
  read -p "enter a: " a
  echo -n "print 2a: "
  return $[ $a * 2 ]
}
fun1
echo "return value $?"
[~/shell/function]# ./return.sh
enter a: 100
print 2a: return value 200

由于shell状态码最大是255,所以当返回值大于255时会出错。

代码如下:
[~/shell/function]# ./return.sh
enter a: 200
print 2a: return value 144

3.函数输出

为了返回大于255的数、浮点数和字符串值,最好用函数输出到变量:

代码如下:
[~/shell/function]# cat ./fun_out.sh
#!/bin/bash
function fun2 {
  read -p "enter a: " a
  echo -n "print 2a: "
  echo $[ $a * 2 ]
}
result=`fun2`
echo "return value $result"
[~/shell/function]# ./fun_out.sh    
enter a: 400
return value print 2a: 800

4.向函数传递参数(使用位置参数):

代码如下:
[~/shell/function]# cat ./parameter.sh
#!/bin/bash
if [ $# -ne 3 ]
then
    echo "usage: $0 a b c"
    exit
fi
fun3() {
    echo $[ $1 * $2 * $3 ]
}
result=`fun3 $1 $2 $3`
echo the result is $result
[~/shell/function]# ./parameter.sh  1 2 3
the result is 6
[~/shell/function]# ./parameter.sh  1 2
usage: ./parameter.sh a b c

5.全局变量与局部变量

默认条件下,在函数和shell主体中建立的变量都是全局变量,可以相互引用,当shell主体部分与函数部分拥有名字相同的变量时,可能会相互影响,例如:
代码如下:
[~/shell/function]# cat ./variable.sh   
#!/bin/bash
if [ $# -ne 3 ]
then
    echo "usage: $0 a b c"
    exit
fi
temp=5
value=6
echo temp is: $temp
echo value is: $value
fun3() {
    temp=`echo "scale=3;$1*$2*$3" | bc -ql`  
    result=$temp

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表