if判断语句

single branch(单分支)

  • 命令格式:

if command; then
   actionfi
  • 举例:

#!/bin/shif [ ! -e /etc/my.cnf ]; then
   touch /etc/my.cnffi解析说明:如果/etc/my.cnf不存在为真;则创建该文件。

dual branch(双分支)

  • 命令格式:

if command1; then
   action1else
   action2fi
  • 举例:

#!/bin/shif [ -f /etc/my.cnf ]; then
   echo "/etc/my.cnf is file type"else
   echo "/etc/my.cnf is not file type"fi解析说明:如果/etc/my.cnf的文件类型是文件为真;则向用户显示这是一个文件不否则向用户显示这不是一个文件

more brach(多分支)

  • 命令格式:

if command1; then
   action1elif command2; then
   action2elif command3; then
   action3fi注意:if语句可嵌套
  • 举例:

#!/bin/shif [ ! -e /etc/my.cnf ]; then
   echo "/etc/my.cnf is not exist"elif [ -d /etc/my.cnf ]; then
   echo "/etc/my.cnf type is directory "elif [ -f /etc/my.cnf ]; then
   echo "/etc/my.cnf type is file"
   else
   echo "/etc/my.cnf is other type"fi解析说明:如果/etc/my.cnf不存在为真,则向用户显示/etc/my.cnf不存在如果/etc/my.cnf的文件类型是目录为真,则向用户显示/etc/my.cnf的类型是个目录如果/etc/my.cnf的文件类型是文件为真,则向用户显示/etc/my.cnf的类型是个文件否则向用户显示/etc/my.cnf的类型是其他

for循环语句

  • 命令格式:

for 变量名 in 列表; do command 变量;done
  • 举例1:

#!/bin/shfor username in user{1..5}; do
    if id $username &>/null; then
       echo "$username is exsit"
       else
       useradd $username && echo "$username" | passwd $username --stdin    fi;done解析说明:将user1作为变量username的值;然后执行如果id user1为真;则向用户显示user1已经存在否则添加用户user1,添加成功后设置user1的密码为user1注:(依次将user1 user2 user3 user4 user5作为变量username的值)
  • 举例2:

#!/bin/shdeclare -i online=0declare -i offline=0for iplist in $(seq 1 254); do
    if ping -w 1 192.168.2.$iplist &>/dev/null;then
    let online++    echo 192.168.2.$iplist online    else
    let offline++    echo 192.168.2.$iplist offline    fidoneecho online count is $onlineecho offline count is $offline解析说明:设置online变量的值为0设置offline变量的值为0将1-254依次赋值给变量iplist然后执行ping命令,如果ping的结果为真,则设置变量online加1并向用户显示ip 在线否则设置变量offline加1并向用户显示ip不在线向用户显示在线一共多少个ip向用户显示不在线一共多少个ip

列表的生成方式:

  • 1.直接给出 如:user1 user2 user3

  • 2.命令结果 如:cat /etc/user  $(cat /etc/user)

  • 3.路径通配 如:/var/*

  • 4.变量引用

执行机制:

依次将“列表“中的值赋值为变量值,每次赋值后执行一次command,直到列表耗尽才停止循环。