【shell】shell if条件判断

shell if条件判断

1.if测试格式

分单分支,双分支和多分支,和一般if测试格式相同

   单分支        双分支           多分支
if 条件测试     if 条件测试     if 条件测试
   命令序列     then 命令序列   then 命令序列
fi             else 命令序列   elif 条件测试1
               fi             then 命令序列
                              ...
                              else 命令序列
                              fi

实例如下

1.1 安装http脚本

[klaus@localhost chapt4]$ cat httpd_yum.sh
#!/bin/bash
read -p "Are you sure to install?[y]:" action

if [ ! "${action}" = "y" ];then
   echo -e "Incorrect input!"
   exit
fi

getway=`ip route | grep 'default via'| awk '{print $3}'`
ping -c1 www.baidu.com &>/dev/null
if [ $? -eq 0 ];then
   sudo yum install httpd httpd-devel httpd-manual httpd-tools -y &>/dev/null
   sudo service httpd start &>/dev/null
   sudo service enable httpd &>/dev/null
   sudo sed -ri '/^#ServerName www.example.com:80=/cServerName www.example.com:80' /etc/httpd/conf/httpd.conf
   sudo sed -ri '/^SELINUX=/cSELINUX=disable' /etc/selinux/config
   curl http://127.0.0.1 &>/dev/null
   if [ $? -eq 0 ];then
       echo "Apache is successfully installed"
   fi
elif ping -c1 $getway &>/dev/null;then
   echo "Check if DNS is correct..."
else
   echo "Check if ip address is correct..."
fi

[klaus@localhost chapt4]$ ./httpd_yum.sh
Are you sure to install?[y]:y
[sudo] password for klaus:
Apache is successfully installed

1.2 根据自己系统版本更换阿里云镜像

我们可以根据阿里提供的镜像源来获取源地址,具体脚本如下

[klaus@localhost chapt4]$ cat ali_mirrors.sh
#!/bin/bash

os_version=`cat /etc/redhat-release|awk '{print $3}'|awk -F "." '{print $1}'`
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup

if [ "$os_version" = "6" ];then
   wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo
   if [ ! $? -eq 0 ];then
       curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo
       if [ $? -eq 0 ];then
           echo "Alibaba Cloud mirror replacement is complete!"
           exit
       else
           echo "Program running error, network unreachable!"
           exit
       fi
       echo "Alibaba Cloud mirror replacement is complete!"
   fi
elif [ "$os_version" = "7" ];then
   wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
   if [ ! $? -eq 0  ];then
       curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
       if [ $? -eq 0  ];then
           echo "Alibaba Cloud mirror replacement is complete!"
           exit
       else
            echo "Program running error, network unreachable!"
            exit
       fi
       echo "Alibaba Cloud mirror replacement is complete!"
   fi
elif [ "$os_version" = "8"  ];then
   wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-8.repo
   if [ ! $? -eq 0  ];then
       curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-8.repo
       if [ $? -eq 0  ];then
           echo "Alibaba Cloud mirror replacement is complete!"
           exit
       else
            echo "Program running error, network unreachable!"
            exit
       fi
       echo "Alibaba Cloud mirror replacement is complete!"
   fi
else
   sudo sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base.repo
fi
[klaus@localhost chapt4]$ sudo ./ali_mirrors.sh
--2020-02-04 08:15:48--  http://mirrors.aliyun.com/repo/Centos-6.repo
Resolving mirrors.aliyun.com... 119.36.51.231, 119.36.51.115, 103.98.81.102, ...
Connecting to mirrors.aliyun.com|119.36.51.231|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2523 (2.5K) [application/octet-stream]
Saving to: “/etc/yum.repos.d/CentOS-Base.repo”

100%[============================================================>] 2,523       --.-K/s   in 0s     

2020-02-04 08:15:48 (229 MB/s) - “/etc/yum.repos.d/CentOS-Base.repo” saved [2523/2523]

[klaus@localhost chapt4]$ ls /etc/yum.repos.d/
CentOS-Base.repo         CentOS-Debuginfo.repo  CentOS-Media.repo  epel.repo
CentOS-Base.repo.backup  CentOS-fasttrack.repo  CentOS-Vault.repo  epel-testing.repo

2.for循环

循环次数固定,循环格式

for 变量名 [in 取值列表]
do
    循环体
done

实例

2.1 批量ping主机地址

[klaus@localhost chapt4]$ ls
ali_mirrors.sh  httpd_yum.sh  ping_batch.sh
[klaus@localhost chapt4]$ cat ping_batch.sh
#!/bin/bash
for i in {2..245}
do
    {
        ip=192.168.84.$i
        ping -c1 -W1 $ip &>/dev/null
        if [ $? -eq 0 ];then
            if [ ! -f ip.txt ];then
                touch ip.txt
            fi
            echo "$ip" | tee -a ip.txt
        fi
    }&
done
wait

echo "finished..."
[klaus@localhost chapt4]$ ./ping_batch.sh
192.168.84.2
192.168.84.129
finished...

2.2 批量创建用户并设置密码

具体的,将用户和密码同时写入一个txt文件中,按照username password的格式

[klaus@localhost chapt4]$ cat user.txt
tmpuser1 123
tmpuser2 456
tmpuser3 789

tmpuser4 000
[klaus@localhost chapt4]$ cat user
useradd_for.sh  user.txt        
[klaus@localhost chapt4]$ cat useradd_for.sh
#!/bin/bash
if [ $# -eq 0 ];then
    echo "usage: `basename $0` file!"
    exit 1
fi

if [ ! -f $1 ];then
    echo "error file!"
    exit 2
fi

IFS=$'\n' #转义字符

for line in `cat $1`
do
    username=`echo "$line" | awk '{print $1}'`
    password=`echo "$line" | awk '{print $2}'`
    
    id $username &>/dev/null
    if [ $? -eq 0 ];then
        echo "user $username" already exists!
    else
        sudo useradd $username
        echo "$password" | passwd --stdin $username &>/dev/null
        if [ $? -eq 0 ];then
            echo "$user is created!"
        fi
    fi
done
[klaus@localhost chapt4]$ chmod a+x useradd_for.sh
[klaus@localhost chapt4]$ ./useradd_for.sh user.txt
[sudo] password for klaus:
[klaus@localhost chapt4]$ awk -F':' '{ print $1}' /etc/passwd
root
bin
...
klaus
win
tmpuser1
tmpuser2
tmpuser3
tmpuser4

3.while循环

while循环格式

while 条件测试
do
    循环体
done

while循环,当条件测试成立时,执行循环体

3.1 实例,批量创建用户并设置密码

[klaus@localhost chapt4]$ cat while_useradd.sh
#!/bin/bash
if [ $# -eq 0 ];then
    echo "usage: `basename $0` file!"
    exit 1
fi

if [ ! -f $1 ];then
    echo "error file!"
    exit 2
fi

#IFS=$'\n'

while read line
do
{
    if [ ${#line} -eq 0 ];then
        continue
    else
        user=`echo "$line" | awk '{print $1}'`
        passwd=`echo "$line" | awk '{print $2}'`
        
        id $user &>/dev/null
        if [ $? -eq 0 ];then
            echo "user $user" already exists!
        else
            sudo useradd $user
            echo "$passwd" | passwd --stdin $user &>/dev/null
            if [ $? -eq 0 ];then
                echo "$user is created!"
            fi
        fi
    fi
}
done < $1
[klaus@localhost chapt4]$ ./while_useradd.sh nameuser.txt
[klaus@localhost chapt4]$ awk -F':' '{ print $1}' /etc/passwd
...
klaus
win
tmpuser1
tmpuser2
tmpuser3
tmpuser

4.until循环

until循环格式

until 条件测试
do
    循环体
done

当条件测试成立(条件测试为假),执行循环体

4.1 网络测试,如果ping不通,延时1s再ping

[klaus@localhost chapt4]$ cat until_ping.sh
#!/bin/bash
ip=4.2.2.2

until ping -c1 W1 $ip &>/dev/null
do
    echo "Network is down, try again after 1s delay..."
    sleep 1
done
[klaus@localhost chapt4]$ ./until_ping.sh
Network is down, try again after 1s delay...
发布了80 篇原创文章 · 获赞 86 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/klaus_x/article/details/104204704