shell (twelve) for loop

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/wzj_110/article/details/100529627

A for loop

语法

    for 变量名 in 变量取值列表

    do

      指令…

    done

Description : In this structure, "the value in the variable list" may be omitted, corresponding to i is omitted n-$ @ , used for i is equivalent to use for i in $ @

Thinking : How to understand the variables list?

The list of files, IP addresses, content and other files!

#!/bin/bash
#for i in 0 1 2 3 4 5       # (1)直接列出来-->序列
#for i in {0..5}            # (2)使用{}的等价方式!
for i in `seq 5`            # (3)命令的输出作为列表
#for i in `ls`              # 查看文件的内容
do
        echo $i
done

seq command

Thought: The more study, the more simplified idea!

Requirement 1 : four each in one row

# 产生{1.10}
seq 10 > a.log
[root@random mnt]# cat a.log |xargs -n4
1 2 3 4
5 6 7 8
9 10
# 专业-->简化的方式!
[root@random mnt]# xargs -n4 < a.log 
1 2 3 4
5 6 7 8
9 10

2, C language type for loop

for((exp1;exp2;exp3))

do

      指令...

done

Requirement 2 : Batch number immediately generate 10

#!/bin/bash
for((i=1;i<=10;i++))
do
  mkdir -p ./test
  touch ./test/`echo $RANDOM|md5sum|cut -c 1-8`_finished.jpg 
done 

Demand 3 : Modify Batch File Name

#!/bin/bash
# 思路:把要改的名字凭借出来!
for i in `ls /root/test`
do
  cd /mnt/test
  # 核心是要改成什么名字
  mv $i `echo $i|sed 's#_finished.jpg#.html#g'`          # sed对应的模式-->对应的文件名字
done 

# 不用rename、awk、sed、只用for循环!

Other equivalent methods added:

# echo $file | sed 's#_finished.html#jpg#g'  -->方法1

# 通过_作为分割符号,分成两个部分-->注意:空格

# $0表示该行、$1表示_前面的部分,通过bash来执行!

ls|awk -F '[_]' '{print "mv " $0,$1".html"}'|bash 

# 比较专业的

rename "_finished.html" ".jpg" *.html 

# 说明:rename "改什么" "改成什么" 对谁进行修改

# for循环就是重复-->要先搞定一个!

Requirements. 4 : for loop 1 + 2 + 3 + ... + 100

#!/bin/bash
for ((i=1;i<=100;i++))
do
  ((sum+=$i))
done
echo "sum=${sum}" 

Equivalents seq generates a list of variables

#!/bin/bash
for i in `seq 100`
do
  let sum+=i
done
echo "sum=${sum}" 

Decomposition of knowledge : a back, and the rest will be up!

The two-cycle process control keyword

break continue exit return 对比

break、continue、exit一般用于循环结构中控制循环(for、while、if)的走向

break n:n表示跳出循环的层数,如果省略n表示跳出"整个循环"

continue n:n表示退到第n层继续循环,如果省略n表示跳过本次循环,"忽略本次"循环的剩余代码,进入循环的下一次循环

exit n:退出"当前shell程序"(脚步),n为返回值。n也可以省略,再下一个shell里通过$?接收这个n值

return n:用于在函数里,作为"函数的返回值",用于判断函数执行是否正确,推出shell程序的对应函数

Exercise 1

#!/bin/bash
for((i=0;i<=5;i++))
do
  if [ $i -eq 3 ];then
  #continue
  #break
  exit
  fi
  echo $i
done
echo "ok" 

# 体会这三者的含义

Follow-up supplement

Guess you like

Origin blog.csdn.net/wzj_110/article/details/100529627