shell双重循环、IFS分隔符、趣味图形、九九乘法表
一、shell脚本值双重循环
1、跳出循环之break命令
for ( (a=1; a<=5; a++) ) do echo "outer loop: $a" for ( (b=1; b<=50; b++) ) do if [ $b-eq 5 ] then break #如果是break 2则代表跳出2层循环 if echo "inter loop: $b" done done
2、中止循环之continue命令
-
continue中止某次循环中的命令,但不会完全中止整个命令
for ((a=1; a<=15; a++) ) do if [ $a -gt 5 ] && [ $a -lt 10 ] then continue fi echo "current value: $a" done
continue和exit的区别
二、IFS分隔符
1、概述
- 默认包含空格,制表符,换行符
- 用 set | grep IFS 命令查看
2、格式
IFS=$' \t\n'
#修改成只换行 IFS=$' \n' IFS=: IFS=',' IFS. OLD=$IFS IFS=$' \n' ... IFS=$IFS.OLD
3、示例
(1)换行符确认
(2)输出环境变量PATH所包含的所有目录以及其中的所有可执行文件
三、shell趣味图形
1、直线
#!/bin/bash for ((a=1;a<=20;a++)) do echo -n "*" done echo ""
2、矩形
#!/bin/bash for ((a=1;a<=10;a++)) do for ((b=1;b<=15;b++)) do echo -n "*" done echo "" done
3、正三角形
#!/bin/bash a=0 while [ $a -le 9 ] do echo -n "*" b=1 while [ $b -le $a ] do echo -n "*" let b++ done echo "" let a++ done
4、倒三角形
#!/bin/bash a=0 while [ $a -le 9 ] do b=8 while [ $b -ge $a ] do echo -n "*" let b-- done echo -n "*" echo "" let a++ done
5、反三角
#!/bin/bash a=0 while [ $a -le 9 ] do b=9 while [ $b -ge $a ] do echo -n " " let b-- done c=0 while [ $c -le $a ] do echo -n "*" let c++ done echo '' let a++ done
6、等腰三角
#!/bin/bash for ((a=1;a<=9;a++)) do for ((b=9;b>=$a;b--)) do echo -n " " done for ((c=1;c<=$[$a*2-1];c++)) do echo -n "*" done echo "" done
7.平行四边形
#!/bin/bash for ((i=6;i>=1;i--)) do for((k=1;k<=i;k++)) do echo -n " " done for (( j=6;j>=1;j--)) do echo -n "*" done echo "" done
8、等腰梯形
#!/bin/bash for ((a=1;a<=9;a++)) do for ((b=9;b>=$a;b--)) do echo -n " " done for ((c=1;c<=9;c++)) do echo -n "*" done for ((d=1;d<=$[$a*2-1];d++)) do echo -n "*" done echo "" done
9、菱形
(1)不可变菱形
#!/bin/bash for ((a=1;a<=9;a++)) do for ((b=9;b>=$a;b--)) do echo -n " " done for ((c=1;c<=$[$a*2-1];c++)) do echo -n "*" done echo "" done for ((d=1;d<=10;d++)) do for ((e=2;e<=$d;e++)) do echo -n " " done for ((f=10;f>=$d;f--)) do echo -n "*" done for ((g=9;g>=$d;g--)) do echo -n "*" done echo "" done
(2)可变大小的菱形
#!/bin/bash read -p "请输入数字: " i for ((a=1;a<=$i;a++)) do for ((b=$i;b>=$a;b--)) do echo -n " " done for ((c=1;c<=$[2*a-1];c++)) do echo -n "*" done echo "" done for ((d=$i-1;d>=1;d--)) do for ((e=$i;e>=$d;e--)) do echo -n " " done for ((f=$d;f>=1;f--)) do echo -n "*" done for ((g=$d;g>1;g--)) do echo -n "*" done echo "" done
四、九九乘法表
#!/bin/bash for ((a=1;a<=9;a++)) # 1~9循环 do for ((b=1;b<=$a;b++)) # 内循环b的值不能超过a do c=$[$a*$b] # a*b等于1*1,2*2 echo -n -e "$a*$b=$c\t" # 输出c的值不换行显示,以及每行空格间隔\t done echo "" # 默认隐藏了换行符 \n done