linux函数及调用

function  sum {

 read -p  "请输入一个数字:" a

 read -p  请输入第二个数字  b

 c=$(($a+$b))

 return $c

}

sum

echo $?

return表示退出函数并返回一个退出值

方法二

sum()  {

 read -p  "请输入一个数字:" a

 read -p  请输入第二个数字  b

 c=$(($a+$b))

 return $c

}

sum

echo $?

返回码必须是0-255,超出的值将除以256取余

超出后结果要取模

加local函数内部变量传不出来

abc () {

 echo  "insert $i"    i=9

 let i++

 local i

 i=8

 echo "inside2 $i"   i=8

}

i=9

abc

echo "outside $i"  i=10

sum () {

    sum=$(($1+$2))

    echo $sum

}

read -p "qingshuru" first

read -p "qingshuru" second

sum $first $second

sum $1 $2 时需要执行时赋值

阶乘函数(递归)函数调用自己的函数

dxl () {

  if [ $1 -eq 1 ]

  then

  echo 1

  else

    local temp=$[ $1-1 ]

    local result=$( dxl $temp )

    echo "$(($1*$result))"

    fi

}

read -p "请输入你要求的阶乘" n

result=`dxl $n`

echo $result

遍历

list_files () {

  for f in `ls $1`

  do  

  if [ -d "$1/$f" ]

   then

   echo $2$f  //$2视为空格区分父子目录可有可无

   list_files "$1/$f" "$2"

  else

    echo "$2$f"

fi

done  

}

list_file  "/opt"

bash -x 分布查看执行

jiafa () {

 result=$[$1+$2]

 echo $result

 }

jianfa () {

  result=$[ $1-$2 ]

  echo $result

}

cengfa () {

  result=$[ $1*$2 ]

  echo $result

}

chufa () {

  if [ $2 -ne 0 ]

then

  result=$[$1/$2]

  echo $result

  else

   echo "$2不能为0"

 fi

}

vim diaoyong.sh

#!/bin/bash

. /opt/hanshu2.sh  source /opt/hanshu2.sh //用绝对路径写

read -p "请输入第一个参数:" first·

read -p "请输入第二个参数:" second

result1=$(jiafa $first $second)

result2=$(jianfa $first $second)

result3=$(chengfa $first $second)

result4=$(chufa $first $second)

echo "加法${result1}"

echo "减法${result2}"

echo "乘法${result3}"

echo "除法${result4}"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值