学习笔记 shell流程控制语句 if 和 for

if条件测试语句
使用单分支的if条件语句来判断/media/cdrom文件是否存在,若存在就结束条件判断和整个Shell脚本,反之则去创建这个目录:

[root@localhost ~]# vim 1.sh
#!/bin/bash
DIR="/media/cdrom"
if [ ! -e $DIR ]
then
mkdir -p $DIR
fi

双分支的if条件语句来验证某台主机是否在线,服务器地址为192.168.162.140

[root@localhost ~]# vim 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 ~]# bash chkhost.sh 192.168.162.140
Host 192.168.162.140 is On-line.
[root@localhost ~]# bash chkhost.sh 192.168.162.150
Host 192.168.1162.150 is Off-line.

有if多分支结构判断成绩“优” “良” “中”

 [root@linuxprobe ~]# vim chkscore.sh
    #!/bin/bash
    read -p "Enter your score(0-100):" n
    if [ $n -ge 85 ] && [ $n -le 100 ] ; then
    echo "优"
    elif [ $n -ge 70 ] && [ $n -le 84 ] ; then
    echo "良"
    else
    echo "中" 
    fi
    [root@localhost ~]# bash 01.sh  
    Enter your score(0-100):97
    优
    [root@localhost ~]# bash 01.sh  
    Enter your score(0-100):50
    中

for条件循环语句
使用for循环从列表中读取多个用户,逐一创建用户账户并设置密码

[root@linuxprobe ~]# vim 1234.txt
andy
barry
carl
duke
eric
george

[root@localhost ~]# vim 02.sh
#!/bin/bash
read -p "Enter The Users Password : " n
for u in `cat 1234.txt`
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 ~]# bash 02.sh
Enter The Users Password : linuxprobe
andy , Create success
barry , Create success
carl , Create success
duke , Create success
eric , Create success
george , Create success

双分支if条件语句与for循环语句相结合,让脚本从主机列表文件ipadds.txt中自动读取IP地址

[root@linuxprobe ~]# vim ip1.txt
192.168.162.141
192.168.162.142
192.168.162.140
[root@linuxprobe ~]# vim 03.sh
#!/bin/bash
HLIST=$(cat ~/ip1.txt)
for IP in $HLIST
do
ping -c 3 -i 0.2 -W 3 $IP &> /dev/null
if [ $? -eq 0 ] ; then
echo "Host $IP is On-line."
else
echo "Host $IP is Off-line."
fi
Done
[root@linuxprobe ~]# bash 03.sh
Host 192.168.162.141 is Off-line.
Host 192.168.162.142 is Off-line.
Host 192.168.162.140 is On-line.

你可能感兴趣的:(学习笔记 shell流程控制语句 if 和 for)