Linux 从入门到跑路第二十三讲 -- 流程控制

博客围绕 Linux Shell 编程展开,介绍了单分支、双分支、多分支 if 语句,case 语句,以及 for、while、until 等循环语句。还给出了查看分区使用率、判断文件类型等具体程序示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单分支 if 语句

if [ 条件判断式 ];then
	程序
fi 

我们编写一个程序,用来查看分区使用率是否超过了我们的预期,如果超过了则发出警告,程序如下:

#!/bin/bash

rate=$(df -h | grep /dev/vda1 | awk '{print $5}' | cut -d "%" -f 1)

if [ $rate -ge 5 ];then
                echo "warn!"
fi

双分支 if 语句

if [ 条件判断式 ]
	then
		条件成立,执行程序
	else
		条件不成立,执行程序
fi

多分支 if 语句

if [ 条件判断式1 ]
	then
		条件成立,执行程序
elif [ 条件判断式2 ]
	then
		条件成立,执行程序
......
else
		所有条件不成立,最后执行程序
fi

我们写一个文件名输入测试程序,根据输入的值判断该文件是属于目录还是普通文件。

#!/bin/bash

read -p "Please input a filename:" file

if [ -z "$file" ]
        then 
                echo "Error!Please input a filename!"
                exit 1
elif [ ! -e "$file" ]
        then
                echo "your input is not a file!" 
                exit 2
elif [ -f "$file" ]
        then 
                echo "$file is a regulare file"
elif [ -d "$file" ]
        then 
                echo "$file is a directory"
else
        echo "$file is an other file"
fi

case 语句

case $变量名 in
	"值1")
		执行程序
		;;
	"值2")
		执行程序
		;;
	*)
		如果变量不是以上的值,执行此程序
		;;
esac

例子如下:

#!/bin/bash

read -p "Please input a number" -t 15 num

case $num in
        "1")
                echo "this is 1"
                ;;
        "2")
                echo "this is 2"
                ;;
        *)
                echo "another number"
                ;;
esac

for 语句

for 变量 in 值1,值2,值3
	do
		程序
	done
for (( 初始值;循环控制条件;变量变化 ))
	do
		程序
	done

例子如下:

#!/bin/bash

s=0

for (( i=1;i<=100;i=i+1 ))
        do
                s=$(( $s+$i ))
        done

echo "the number is $s"

while 语句

while [ 条件判断式 ]
	do
		程序
	done
#!/bin/bash

s=0;
i=1;

while [ $i -le 100 ]
        do
                s=$(( $s+$i ))
                i=$(( $i+1 ))
        done

echo "the number is $s"

until 语句

until [ 条件判断式 ]
	do
		程序
	done
#!/bin/bash

s=0
i=1

until [ $i -gt 100 ]
        do
                s=$(( $s+$i ))
                i=$(( $i+1 ))
        done

echo "the number is $s"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值