寒假Shell作业_02

题目:

在这里插入图片描述

1.

#!/bin/bash
ip="192.168.1." #设置网段
for i in `seq 1 255`
do
        ping -c 1 $ip$i &>/dev/null #看能否ping通
        if [ $? -eq "0" ];then #看退出状态码
                echo -e "$ip$i is up"
        else
                echo -e "$ip$i is down"
        fi
done

$?显示最后命令的退出状态。0表示没有错误,其他任何值表明有错误。

2.

#!/bin/bash
sum=0
for (( i=0;i<=100;i++ )) #用for循环来遍历100以内的数
do
    if test $((i%2)) -eq 0 #判断是否为偶数
    then
        let sum+=i #若是偶数则进行累加(也可写成sum=$[ $sum + $i ])
    fi
done
echo "sum = "$sum #输出结果


方法二:
#!/bin/bash
sum=0
for (( i=0;i<=100;i+=2 )) #用for循环来遍历100以内的数
do
    let sum+=i #若是偶数则进行累加(也可写成sum=$[ $sum + $i ])
done
echo "sum = "$sum #输出结果

#方法三:
#!/bin/bash
for i in {0..100..2}
do
       sum=$(($sum+$i))
done
echo "100以内偶数之和为"$sum

3.

#!/bin/bash
read -p "Please enter the number and what you want to do:(eg:7 + 8) " a b c #输入数字和操作符
echo "$a$b$c = "
echo "$a$b$c"|bc #计算结果并输出

4.

#!/bin/bash
read -p "Please choose one you want to know and enter its number :  1:cpu 2:mem 3:disk 4:quit  " result
if [ $result == 1 ]
then
    cat /proc/cpuinfo
elif [ $result == 2 ]
then
    free -h |head -2
elif [ $result == 3 ]
then
    df -Th
elif [ $result == 4 ]
then
    echo "See you"
else
    echo "Input error,please enter again"
fi

5.

#!/bin/bash
read -p "Please enter what you want to do :" result #接收用户输入的变量
lockfile="/var/lock/subsys/SCRIPT_NAME"
if [ $result == start ] #根据用户输入的内容,作相应的事情
then
    touch $lockfile
    echo "this service is start"
elif [ $result == stop ]
then
    rm -rf $lockfile
    echo "this service is stop"
elif [ $result == restart ]
then
    rm -rf $lockfile
    touch $lockfile
    echo "this service is restart"
elif [ $result == status ]
then
    if [ -e $lockfile ]
    then
        echo "The service is running"
    else
        echo "The service is stopped"
    fi
else
    echo "Input error,please enter again"
fi

猜你喜欢

转载自blog.csdn.net/kang19970201/article/details/87554263