【转】Shell编程进阶篇(完结)

  

1.1 for循环语句

     在计算机科学中,for循环(英语:for loop)是一种编程语言的迭代陈述,能够让程式码反复的执行。

     它跟其他的循环,如while循环,最大的不同,是它拥有一个循环计数器,或是循环变数。这使得for循环能够知道在迭代过程中的执行顺序。

1.1.1 shell中的for循环

         shell中的for 循环与在c中不同,它包含三种形式:第一种结构是列表for 循环;第二种结构就是不带列表的for循环;第三种就类似于C语言。

①   列表for循环(常用)

#!/bin/bash
for i in 取值列表
do
    循环主体/命令
done

 

②   不带列表for循环(示例)

#!/bin/absh
echo "惨绿少年的博客是:"  
for i 
     do   
     echo "$i" 
done 

   脚本执行结果

[root@clsn for]# sh  for2.sh http://blog.znix.top
惨绿少年的博客是:
http://blog.znix.top

 

 【转】Shell编程进阶篇(完结)

③   类似C语言的风格这种用法常在C语语言中使用)

for((exp1;exp2;exp3))
    do
      指令...
done   

         编写类似C语言风格脚本

for((i=0;i<=3;i++))
    do
      echo $i
done  

         脚本执行过程

【转】Shell编程进阶篇(完结) 

1.1.2 不同语言的For循环

Shell中的两种样式

# 样式一:
for i in 1 2 3 
  do 
    echo $i
done
# 样式二:
for i in 1 2 3;do  echo $i;done

  JAVA

for(int i = 0; i < 5; i++){
    //循环语句;
}

  PHP

for ($i = 0; $i < 5; $i++) {
  # statements;
}

  VB

For i = 1 To 5
===PASCAL===
for not i=1 do
begin
   i=0;
   writeln('Go on!');
end.
   
  '循环语句
Next i

  swift

var x = 0
for i in 1...100{
    x += i
}
print(x)

//5050
for _ in 1...100{
    x += 1
}
print(x)
// 100

var box = [1,2,3,4,5]
for i in box{
    print(i)
}
/*
1 
2 
3 
4 
5
*/
---

1.2 for循环相关练习题

1.2.1 【练习题1】批量生成随机字符文件名案例

使用for循环在/clsn目录下批量创建10个html文件,其中每个文件需要包含10个随机小写字母加固定字符串clsn,名称示例如下:

[root@znix C19]# ls /clsn
apquvdpqbk_clsn.html  mpyogpsmwj_clsn.html  txynzwofgg_clsn.html   
bmqiwhfpgv_clsn.html  udrzobsprf_clsn.html  vjxmlflawa_clsn.html  
jhjdcjnjxc_clsn.html  qeztkkmewn_clsn.html jpvirsnjld_clsn.html  
ruscyxwxai_clsn.html

脚本内容

 1 [root@clsn for]# cat make_file.sh 
 2 #!/bin/bash
 3 #############################################################
 4 # File Name: make_file.sh
 5 # Version: V1.0
 6 # Author: clsn
 7 # Organization: http://blog.znix.top
 8 # Created Time : 2017-12-08 11:01:19
 9 # Description:
10 #############################################################
11 
12 [ -d /clsn ] || mkdir -p /clsn
13 rpm -qa |grep pwgen &>/dev/null
14 if [ $? -eq  1 ] 
15   then 
16     yum install pwgen -y &>/dev/null
17 fi
18 
19 cd /clsn &&\
20 for i in {1..10}
21   do
22    #File_Name=`uuidgen |tr "0-9-" "a-z"|cut -c 1-10`
23    File_Name2=`pwgen -1A0 10`
24    touch ${File_Name2}_clsn.html
25 done
View Code 批量生成随机字符文件名

相关文章:

  • 2021-12-25
  • 2021-09-29
  • 2021-09-12
  • 2022-12-23
  • 2018-11-20
  • 2021-08-02
  • 2022-01-19
  • 2021-09-14
猜你喜欢
  • 2021-11-20
  • 2021-11-05
相关资源
相似解决方案