bash脚本循环语句用法练习
1、使用循环语句写一个脚本,实现打印出来国际象棋的棋盘
#方法1:使用until循环语句实现 [root@liang7 bin]# cat chess-until.sh #!/bin/bash #Author:liang #Version:1.0 #Description:Print the chess board #Define the number of rows r=1 until [ $r -gt 8 ] ; do #Define the number of columns c=1 until [ $c -gt 8 ] ; do if [ `echo $[(r+c)%2]` -eq 0 ] ;then echo -ne "\033[43m \033[0m" else echo -ne "\033[41m \033[0m" fi let c++ done echo let r++ done #方法2;使用while循环语句实现 [root@liang7 bin]# cat chess-while.sh #!/bin/bash #Author:liang #Version:1.0 #Description:Print the chess board #Define the number of rows r=1 while [ $r -le 8 ] ; do #Define the number of columns c=1 while [ $c -le 8 ] ; do if [ `echo $[(r+c)%2]` -eq 0 ] ;then echo -ne "\033[43m \033[0m" else echo -ne "\033[41m \033[0m" fi let c++ done echo let r++ done #方法3:使用for循环语句实现 [root@liang7 bin]# cat chess-for.sh #!/bin/bash #Author:liang #Version:1.0 #Description:Print the chess board #Define the number of rows for r in {1..8} ; do #Define the number of columns for c in {1..8} ; do if [ `echo $[(r+c)%2]` -eq 0 ] ;then echo -ne "\033[43m \033[0m" else echo -ne "\033[41m \033[0m" fi done echo done
2、使用循环语句写一个脚本,实现用“*”打印出等腰三角形的形状
#方法1: [root@liang7 bin]# cat sjx1.sh #!/bin/bash #Author:liang #Version:1.0 #Description:Print out an isosceles triangle read -p "请输入想要的三角形层数:" num until echo $num|grep -q '^[0-9]\+$' ; do read -p "请重新输入三角形层数:" num done if [ $num -eq 0 -o $num -eq 1 ] ; then echo "您输入的层数无法组成三角形,输入的层数应大于等于2" else for line in `seq 1 $num`; do let n=$num-$line m=1 while [ $n -gt 0 ] ; do echo -n " " let n-- done while [ `echo $[line*2-1]` -ge $m ]; do echo -n "*" let m++ done echo done fi 方法2: [root@liang7 bin]# cat sjx2.sh #!/bin/bash #Author:liang #Version:1.0 #Description:Print out an isosceles triangle read -p "请输入想要的三角形层数:" num until echo $num|grep -q '^[0-9]\+$' ; do read -p "请重新输入三角形层数:" num done if [ $num -eq 0 -o $num -eq 1 ] ; then echo "您输入的层数无法组成三角形,输入的层数应大于等于2" else for line in `seq 1 $num` ; do for((n=(num-line);n>0;n--)); do echo -n " " done for((m=1;(line*2-1)>=m;m++)); do echo -n "*" done echo done fi
原创文章,作者:苦涩咖啡,如若转载,请注明出处:http://www.178linux.com/37114