|NO.Z.00027|——————————|LinuxShell|——|Linux&Shell&流程控制.V08|——|函数|

一、条件判断——函数
### --- 函数语法

function 函数名 () {
    程序
}
二、条件判断——函数实验
### --- 实例一:从 1 加到 100 了,我们让用户自己来决定加到多少吧:

[root@localhost ~]# vi sh/function.sh
#!/bin/bash
#接收用户输入的数字,然后从 1 加到这个数字
# Author: shenchao (E-mail: shenchao@atguigu.com)


function sum () {
#定义函数 sum
        s=0
        for (( i=0;i<=$1;i=i+1 ))
        #循环直到 i 大于$1 为止。$1 是函数 sum 的第一个参数
        #在函数中也可以使用位置参数变量,不过这里的$1 指的是函数的第一个参数
                do
                            s=$(( $i+$s ))
                done
        echo "The sum of 1+2+3...+$1 is : $s"
        #输出 1 加到$1 的和
}

read -p "Please input a number: " -t 30 num
#接收用户输入的数字,并把值赋予变量 num
y=$(echo $num | sed 's/[0-9]//g')
#把变量 num 的值替换为空,并赋予变量 y
if [ -z "$y" ]
#判断变量 y 是否为空,以确定变量 num 中是否为数字
        then
                sum $num
                #调用 sum 函数,并把变量 num 的值作为第一个参数传递给 sum 函数
        else
                echo "Error!! Please input a number!"
                #如果变量 num 的值不是数字,则输出报错信息
fi

 
 
 
 
 
 
 
 
 

Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
                                                                                                                                                   ——W.S.Landor

 

 

posted on   yanqi_vip  阅读(11)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示