示例:shell循环控制for、while语句

本文详细介绍了C语言中的for和while循环实现乘法表,创建30个用户并设置密码,以及利用循环检测网络段内IP的ping与ssh操作。通过实例展示了多种循环技巧在信息技术中的实际应用。

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

1.9 * 9 乘法表,for列表循环,for循环(c语言风格), while循环
可选单层循环

#! /bin/bash

echo "==================for i in list==================="
for i in `seq 9`
do
    for j in `seq $i`
    do
        echo -n "$i*$j=$[i*j] "
    done
    echo
done

echo "==================for(())==================="


for((i=1,j=1;i<=9;j++))
do
    echo  -n  "$i*$j=$[i*j] "

    if [ $i == $j ];then
        echo -e '\n'
        let j=0
        let i=$i+1
    fi
done

echo "==================while==================="

let i=1;
while ((i<=9))
do
    let j=1;
    while (($j<=$i))
    do
        echo -ne "$i"*"$j=$[i*j]\t"
        let j++;
    done
echo ""
let i++;
done

2.使用for循环创建30个用户: test01~test30, 并设置密码为test01 123456~test30 123456

for i in `seq -f '%02g' 1 30`
do

    if id -u $i &> /dev/null;then
        echo test$i is exist!
        continue
    fi
        useradd test$i
        echo "test'$i'123456" | passwd --stdin test$i &> /dev/null

done

3.使用循环去判断网段内的IP(1~254),本机除外,可以ping通的使用 ssh远程登录

for i in `seq 1 254`
do
   if [ $i -eq 135 ];then
        continue
   else 
        ping -c 2 -w 1 192.168.10.$i &> /dev/null
        if [ $? -eq 0 ];then
            ssh 192.168.10.$i
        fi
    fi
done

4.使用 @ 和 @和 @*作为for循环后的列表,并体现出区别

[root@servera bash]# bash @and\*.sh this is a example
echo "============$ @================"
for i in "$@"
do
    echo $i
done

echo "============$ *================"
for i in "$*"
do
    echo $*
done

[root@servera bash]# bash @and*.sh  this is a example
============$ @================
this
is
a
example
============$ *================
this is a example
[root@servera bash]#

5.使用循环去读取文件内容并输出: 3中方式(1.exec+while循环 2.管道符+while循环 3.重定向+while)

[root@servera bash]# echo data{1..3} > file.txt
echo "============= methon 1:exec+while ================"

exec < file.txt
while read a
do
    echo $a
done


echo "============= methon 2: | +while ================"
cat file.txt | while read line
do
    echo $line
done


echo "============= methon 3: < +while ================"
while read line
do
    echo $line
done < file.txt

[root@servera bash]# bash while_read.sh 
============= methon 1:exec+while ================
data1 data2 data3
============= methon 2: | +while ================
data1 data2 data3
============= methon 3: < +while ================
data1 data2 data3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值