Linux(ubuntu)shell脚本条件判断函数和循环(入门必看)

发布于:2022-12-22 ⋅ 阅读:(303) ⋅ 点赞:(0)

目录

一.shell脚本条件判断

1. if  then 语句写法

2. if then else 语句写法

3. if  elif else  语句写发

 二.shell 脚本函数

1.  函数的简单使用

2.函数的传参:

三.shell 循环

1.while   do  done  循环

2.  until  do   done  循环

 3.for循环


一.shell脚本条件判断

        shell脚本之处条件判断,虽然可以通过&&和||来实现简单的条件判断,但是稍微复杂一点的场景就不适合了,shell脚本提供了if  then 的条件判断语句,写法。

1. if  then 语句写法

        if [条件判断] ;then

        //条件判断成立要做的事情

        fi   (结束)

 编写:

执行: 

2. if then else 语句写法

        if   【条件判断】; then

  //条件判断成立要做的事情

        else   【条件】

    //条件判断不成立要做的事情

    fi    //结束

 编写:

 执行:

3. if  elif else  语句写发

if【条件判断】;then

//条件判断成立要做的事情

elif 【条件判断】;then

//条件判断成立要做的事情

else

//条件判断不成立要做的事情

fi

case 语句写法

case $变量   in

        "第一个变量内容")

        程序段

        ;;      //表示该程序块结束

        "第二个变量内容")

        程序段

        ;;

        "第n个变量内容")

        程序段

        ;;

esac

编写:

执行:

 二.shell 脚本函数

1.  函数的简单使用

例如:

function fname (参数){

        //函数代码段

}

#!/bin/bash
function help(){
    echo "this is help cmd!"
}
function close(){
    echo "this is close cmd!"
}
case s1 in
        "-h")
        help
        ;;
        "-c")
        close
        ;;
esae

2.函数的传参:

#!/bin/bash
print(){
        echo "param 1:$1"
        echo "param 2:$2"
}
print a b

三.shell 循环

1.while   do  done  循环

        while [括号]     //括号内的状态是判断式

        do                  //循环开始

                  //循环代码

        done

#!/bin/bash
while [ "$value" != "close" ]
do
    read -p "please input str:" value
done
    echo "stop while!!"

执行: 直到输入  close  循环结束

2.  until  do   done  循环

until[条件]        //不成立开始循环

do

//循环代码段

done

 3.for循环

for var in con1  con2  con3  ......

do

//循环体

done    

 编写:

#!/bin/bash
for name in bit1 bit2 bit3 bit4
do
    echo "your name: $name"
done

 4.for 循环数值处理写法

for((初始值;限制值;执行步长))

do

//循环代码段

done

编写: 

#!bin/bash
read -p"please input count:" count
total=0
for((i=0;i<=count;i=i+1))
do 
    total=$(($total+$i))
done
echo "1+2+···+$count=$total"

 执行:


网站公告

今日签到

点亮在社区的每一天
去签到