shell之 函数(Function)

2025-09-27 13:27:15

1、1、函数传入参数

[oracle@rhel6 zxx_shell]$ cat 2-function.sh 

#!/bin/bash

function show_week()

{

  local week1=$1   #表示将第一个参数传给本地变量week1

  local week2=$2  #表示将第二个参数传给本地变量week2

  declare -i total    #表示声明一个整型变量

  let total=$week1*$week2  #将变量week1和变量week2的乘积赋值给total

  echo "week1=$week1"

  echo "week2=$week2"

  echo "total=$total"

}

show_week 3 4   #调用函数,调用时传入参数

[oracle@rhel6 zxx_shell]$ ./2-function.sh 

week1=3

week2=4

total=12

shell之 函数(Function)

2、2、函数通过全局变量返回值

[oracle@rhel6 zxx_shell]$ cat 2-function.sh 

#!/bin/bash

 total=          #全局变量

function show_week()

{

  local week1=$1       #local 表示本地变量

  local week2=$2

  total=$[$week1*$week2]   #赋值给全局变量

}

  num1=3

  show_week $num1 "4"

  echo "================="$total

[oracle@rhel6 zxx_shell]$ ./2-function.sh 

=================12

shell之 函数(Function)

3、3、函数通过echo返回值

[oracle@rhel6 zxx_shell]$ cat 2-function.sh 

#!/bin/bash

function show_week()

{

  local week1=$1

  local week2=$2

  let total=$week1*$week2

  echo $total   #通过echo标准输出返回函数值

}

  num1=3

  num2=$(show_week $num1 "4")  #调用函数并将函数返回值赋值给变量

  echo "================="$num2

[oracle@rhel6 zxx_shell]$ ./2-function.sh 

=================12

shell之 函数(Function)

4、4、函数相互调用

[oracle@rhel6 zxx_shell]$ cat 2-function.sh 

#!/bin/bash

 total=

function show_week()

{

  local week1=$1

  local week2=$2

  total=$[$week1*$week2]

}

function getvalue()

{

  num1=$1

  num2=$2

  show_week $num1 $num2  #调用show_week函数

  echo "=================$total"  #注意调用函数getvalue时,不    #会打印这个,它是作为返回值的

}

  num3=3

  num4=3

  var=$(getvalue $num3 $num4)

  echo "var string value is:$var"

[oracle@rhel6 zxx_shell]$ ./2-function.sh 

var string value is:=================9

shell之 函数(Function)

5、5、一个函数调用多个函数

[oracle@rhel6 zxx_shell]$ cat 2-function.sh 

#!/bin/bash

function show_week()

{

  local week1=$1

  local week2=$2

  total=$[$week1 * $week2]    #传入参数的两个计算乘积,并返回

  echo $total 

}

function getvalue()

{

  date1=`date +%w`  #计算今天周几

  echo $date1

}

function getchushu()

{

  num1=$1

  num2=$2

  var1=$(show_week $num1 $num2)

  var2=$(getvalue)

  var3=$[$var1 / $var2]   #计算两个函数返回值的除数

  echo $var3

}

  num3=5

  num4=2

  var4=$(getchushu $num3 $num4)

  echo "var4 string value is:$var4"

[oracle@rhel6 zxx_shell]$ ./2-function.sh 

var4 string value is:3

shell之 函数(Function)

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢