脚本练习

脚本练习

1.编写shell脚本,实现1-100的猜数字游戏

#!/bin/bash
###
## RANWOM -lt 100
b=$(expr $RANDOM % 100)                              //1-100的随机数
while [ true ]                                       //无限循环,true表示真,跳出循环需要用break
read -p "please type a number(1-100):" a
     do
        if [ -s `echo $b | sed s/[0-9]//g` ];then    // 将数字删除掉,该值还非空时
            if [ $a -gt 0 -a $a -lt 100 ];then
                if [ $a -lt $b ];then
                   echo "The number entered is small"
                elif [ $a -gt $b ];then
                   echo "The number entered is large"
                elif [ $a -eq $b ];then
                   echo "You got it right"
                break
                else
                   echo "Please enter the correct number"
                fi
            else
                   echo "please enter number(1-100) "
            fi
        else
            echo "please enter number"
        fi
done

2.编写shell脚本,计算1-100的和

#!/bin/bash
##
sum=0
for i in  `seq 1 100` ;do
let sum="$i+$sum"
done
echo $sum

运行

[root@xiefei ~]# sh c.sh
5050

3.编写shell脚本,要求输入一个正整数,然后计算出从1到输入数字的和,要求如果输入的数字小于1,则重新输入,直到输入正确的数字为止

#!/bin/bash
while [ true ];do
read -p "please type a number:" a
        if [ $a -lt 1 ];then
            echo "Please enter the correct number"
        else
                sum=0
                for i in `seq $a`;do
                let sum=$i+$sum
                done
                echo $sum
                break
        fi
done

4.编写shell脚本,批量建立用户user_00,user_01,…user_100并且所有用户同属于users组

#!/bin/bash
### useradd
source /root/userdel.sh //先删除后创建
read -p "输入一个数字:" a
for i in $(seq $a);do  //输入多少创建多少用户 创建100个就输入100
    username=$i
    useradd user_$username -g users &> /dev/null
    echo "123.com" | passwd --stdin $username &> /dev/null
done

批量删除

#!/bin/bash
####userdel
read -p "请输入数字:" a
for i in $(seq $a);do
    username=user_$i
    userdel  -r $username &> /dev/null
done

你可能感兴趣的:(脚本练习)