学习笔记之shell脚本基础(二)

Shell----if&for

判断文件是否存在

[root@localhost ~]# vi 1.sh
[root@localhost ~]# bash -x 1.sh
+ l=123/121
+ '[' '!' -e 123/121 ']'
+ mkdir -p 123/121
[root@localhost ~]# cat 1.sh
#!/bin/bash

l="123/121"
if [ ! -e $l ]
then
mkdir -p $l
fi
[root@localhost ~]#

验证某台主机是否在线

[root@localhost ~]# vi 2.sh
[root@localhost ~]# bash 2.sh 8.8.8.8
Host 8.8.8.8 is On-line.
[root@localhost ~]# bash 2.sh 10.0.0.1
Host 10.0.0.1 is Off-line.
[root@localhost ~]# cat 2.sh
#!/bin/bash

ping -c 3 -i 0.2 -W 3 $1 &> /dev/null
if [ $? -eq 0 ]
then
echo "Host $1 is On-line."
else
echo "Host $1 is Off-line."
fi
[root@localhost ~]#

判断用户输入的分数在哪个成绩区间内

[root@localhost ~]# vi 3.sh
[root@localhost ~]# bash 3.sh 
Enter your score(0-100):88
88 is Excellent
[root@localhost ~]# bash 3.sh 
Enter your score(0-100):66   
66 is Fail
[root@localhost ~]# bash 3.sh 
Enter your score(0-100):77
77 is Pass
[root@localhost ~]# bash 3.sh 
Enter your score(0-100):111
Error
[root@localhost ~]# bash 3.sh 
Enter your score(0-100):-11
Error
[root@localhost ~]# cat 3.sh 
#!/bin/bash

read -p "Enter your score(0-100):" n
if [ $n -ge 85 ] && [ $n -le 100 ] ; then
echo "$n is Excellent"
elif [ $n -ge 70 ] && [ $n -le 84 ] ; then
echo "$n is Pass"
elif [ $n -ge 100 ] || [ $n -le 0 ] ; then
echo "Error"
else
echo "$n is Fail" 
fi
[root@localhost ~]#

同时创建多个用户

[root@localhost ~]# vi users
[root@localhost ~]# cat users
xb
xl
xu
[root@localhost ~]# vi 4.sh
[root@localhost ~]# bash 4.sh 
Enter The Users Password : 123
xb , Create success
xl , Create success
xu , Create success
[root@localhost ~]# cat 4.sh 
#!/bin/bash

read -p "Enter The Users Password : " n
for u in `cat users`
do
id $u &> /dev/null
if [ $? -eq 0 ]
then
echo "Already exists"
else
useradd $u &> /dev/null
echo "$n" | passwd --stdin $u &> /dev/null
if [ $? -eq 0 ]
then
echo "$u , Create success"
else
echo "$u , Create failure"
fi
fi
done
[root@localhost ~]#

同时测试多主机是否在线

[root@localhost ~]# vi iplist 
[root@localhost ~]# cat iplist 
192.168.159.140
8.8.8.8
114.114.114.114
192.168.159.130
[root@localhost ~]# vi 5.sh
[root@localhost ~]# bash 5.sh 
Host 192.168.159.140 is On-Line.
Host 8.8.8.8 is On-Line.
Host 114.114.114.114 is On-Line.
Host 192.168.159.130 is Off-Line
[root@localhost ~]#
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值