shell 脚本之if、for、while语句

本文介绍了Shell脚本的基础语法,包括if条件判断、for循环和while循环的具体用法及示例。通过不同的示例展示了如何在Bash环境下进行变量比较、数值运算以及字符串操作等。

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

(1)if语句

root@ubuntu:/mnt/shared/shellbox/shellif# cat shellif.sh 
#!/bin/bash

#推断字符串
if [ "$1" = "hello" ]
then
        echo "\$1=$1"
fi

#推断数字,if()方式仅仅能在bash下用,在sh下不行
if ((  $1 > 20 ))
then
        echo "\$1: $1 > 20"
elif (( $1 == 20 ))
then
        echo "\$1 == 20"
elif (( $1 < 20 ))
then
        echo "\$1 < 20"
fi

#方括号推断语句
if [ $1 -lt 20 ]
then
        echo "\$1 < 20"
elif [ $1 -ge 20 -a $1 -le 30 ]
then
        echo "\$1 >= 20 && \$1 <= 30 "
elif [ $1 -gt 30 ]
then
        echo "\$1 > 30"
fi

运行结果:

root@ubuntu:/mnt/shared/shellbox/shellif# ./shellif.sh 10
$1 < 20
$1 < 20
root@ubuntu:/mnt/shared/shellbox/shellif# ./shellif.sh 20
$1 == 20
$1 >= 20 && $1 <= 30 
root@ubuntu:/mnt/shared/shellbox/shellif# ./shellif.sh 30
$1: 30 > 20
$1 >= 20 && $1 <= 30 
root@ubuntu:/mnt/shared/shellbox/shellif# ./shellif.sh 40
$1: 40 > 20
$1 > 30


(2)for语句

root@ubuntu:/mnt/shared/shellbox/shellfor# cat shellfor.sh 
#!/bin/bash

for i in $*
do
        echo $i
done

for char in {a..c}
do
        echo $char
done


for int in {1..3}
do 
        echo $int
done

运行结果:

root@ubuntu:/mnt/shared/shellbox/shellfor# ./shellfor.sh 
a
b
c
1
2
3


(3)while语句:

root@ubuntu:/mnt/shared/shellbox/shellwhile# cat shellwhile.sh 
#!/bin/bash

#注意: (( ))这样的方式仅仅能在bash中使用,而不能在sh中使用
i=0
while (( i < $1 ))
do
    echo "i=$i"
    let i+=1
done

#赋值时"="前后不能有空格
num=0
while [[ $num != $1 ]]
do
        echo "num=$num, num != \$1"
        let num+=1
done

while true
do
        echo "here in while true ..."
        sleep 2
done
运行结果:



root@ubuntu:/mnt/shared/shellbox/shellwhile# ./shellwhile.sh 5
i=0
i=1
i=2
i=3
i=4
num=0, num != $1
num=1, num != $1
num=2, num != $1
num=3, num != $1
num=4, num != $1
here in while true ...
here in while true ...

转载于:https://www.cnblogs.com/zfyouxi/p/5067372.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值