Detailed Explanation of Shell Loop Statement--for Loop


Introduction: In shell programming, in addition to selection and judgment, loop operations are required for some special cases, such as traversing directory files, adding users in batches, etc., all require loop operations

1. Basic format of for loop

Grammar format:

for 变量名 in 取值列表
do
  命令
done

insert image description here
The number of for loop executions depends on the number of variables in the value list

for i in {
    
    1..5};do echo $i;done
{
    
    1..5}为取值范围1到5
echo $i 输出当前的取值

insert image description here

for((i=1;i<=5;i++));do echo $i;done
使用(())双括号,可以支持C语言的一些命令
i=1;i<=5;i++ #i初始值为1,如果i小于等于5时执行循环,每次循环后+1

insert image description here

for i in `seq 5`;do echo $i;done
seq 5{
    
    1..5}效果一样

insert image description here

for i in `seq 5`;do echo "hello world";done
使用变量i 循环5次
每次执行echo "hello world"命令

insert image description here
Use a for loop to traverse the current directory
insert image description here

2. for loop script

A simple script implemented using a for loop

2.1 Test host status

Detect the survival status of the host in the LAN

#!/bin/bash
for IP in `cat /root/for/ip.txt`    #ip文件为存放ip地址的
do
  ping -c 3 -i 0.2 -w 3 $IP &>/dev/null #-c 3 ping3次主机 -i 0.2ping主机间隔 -w 3ping主机超时间隔
  if [ $? -eq 0 ];then
  echo "host $IP is up"
  else echo "host $IP is down"
  fi
done

insert image description here

insert image description here

2.2 Add users

Use for loop and if conditional statement to add users in batches

#!/bin/bash
for user in `cat /root/for/a.txt`    #a.txt为存放用户名单文件
do
  if grep $user /etc/passwd &>/dev/null; then   #检查用户是否存在 
     echo "$user用户已经存在"
  elif [ -d /home/$user ];then          #检查home下是否存在和用户相同的目录 
     echo "$user用户存在宿主目录"    
  else useradd $user                    #添加用户并设置初始密码 
       echo "123456" |passwd --stdin $user &>/dev/null  
       echo "$user用户已经创建,初始密码为:123456"
  fi
done

insert image description here

insert image description here
The user status exists or is abnormal
insert image description here

2.3 Multiplication table

Use the for loop to print the 99 multiplication table

#!/bin/bash
for ((i=1;i<=9;i++))     #此处也可以写  for i in {1..9}
  do
     for ((j=1;j<=i;j++))  #此处也可写 for j in `seq $i`
       do echo -n -e "$j*$i=$[j*i]\t" #-n不换行输出;-e使用\转义符;\t横向制表;若不用-e,则\t为普通字符
       done
  echo
  done

insert image description here
insert image description here

3. Summary

1. The for loop is used a lot in actual generation, avoiding manual repeated operation of something
2. The list in the for loop supports regular expressions
3. (()) is used in the for loop, and the C language is supported in double brackets Command
4. The variable in the for loop just loops to get the value in the value list, and then performs the do operation, so the number of parameters in the value list determines the number of cycles

Guess you like

Origin blog.csdn.net/weixin_44175418/article/details/124444938
Recommended