自学shell编程——第3讲(for语句/while语句/until语句)
三种循环语句:for语句/while语句/until语句。
1. for循环语句:for 循环变量 in 次数-do-循环体-done
以一个例子作为练习,熟悉for循环语句。这里比较难的是次数(就是循环限制)的书写
#在定义变量时定义属性
declare -i num=2 #将变量nun直接定义为整数型,值为2
num=$num*2;echo $num #输出4;若是前面直接为num=2,则输出2*2
#计算2^10的结果1024,命令行输入2和10
result=1 #当然这里你可以使用declare -i result=1,那么下面的result=$result*$1
for num in `seq 1 $2` #循环变量为num,每次循环+1
do
result=`expr $result \* $1`
done
echo $result #执行:./for.sh 2 10;输出1024
#计算1+2+3+……+100的结果5050,命令行输入1和100
declare -i result=0
for num in `seq $1 $2`
do
result=$result+$num
done
echo $result #执行:./for.sh 1 100;输出5050。执行:./for.sh 2 10;输出54
#将命令行参数依次输出,这里是对$*进行遍历
declare -i n=1
for argu in $*
do
echo "argument $n is $argu."
n=$n+1
done #执行:./for.sh 1 100;输出argument 1 is 1. argument 2 is 100.
#对数组内容进行遍历
name="zhao qian sun li"
declare -i n=1
for argu in $name
do
echo "argument $n is $argu."
n=$n+1
done #执行:./for.sh;输出argument 1 is zhao. argument 2 is qian. argument 3 is sun. argument 4 is li.
简单小结:for可以执行一定次数的循环,也可以对数组进行遍历。多多联系,习惯书写,还是有很多小坑需要自己踩一踩
2. while循环语句:while 判断条件-do 循环体-done
以一个例子作为练习,熟悉while循环语句。判断条件的书写:使用test测试语句或者[],循环体内书写如何循环。
#!/bin/bash
#计算两个数之间所有偶数的和。(2-10:2+4+6+8+10;3-10:4+6+8+)
declare -i i
declare -i sum=0 #书写习惯,在使用变量前先定义变量。i为循环变量,sum为累积
#这里对输入的两个数进行判断,第一个数,若为偶数,则保留;否则加1。第二个数,若为偶数,则保留;否则减1
if [ `expr $1 \% 2` -eq 0 ]
then
i=$1;
else
i=`expr $1 + 1`
fi
if [ `expr $2 \% 2` -eq 0 ]
then
end=$2;
else
end=`expr $2 - 1`
fi
while [ $i -le $end ] #-le表小于等于
do
sum=$sum+$i
i=$i+2 #每次加2
done
echo $sum #执行:./while.sh 2 10,输出30;./while.sh 3 9;输出18;./while.sh 3 10;输出28
#计算10!,输出3,628,800
declare -i i=1
declare -i result=1 #书写习惯,在使用变量前先定义变量。i为循环变量,sum为累积
while test $i -le $2
do
result=$result*$i
i=$i+1
done
echo $result #执行:./while.sh 2 10,输出3,628,800;
这里加一个小小的需要思考的题目。(这里你先思考一下,再看给出的答案,输出结果即可,不一定和我的相同)键盘输入3,输出图形
;输入4,输出图形
#!/bin/bash
if test $# -ne 1 #判断输入一个参数
then
echo "input one arguments."
fi
#这里将这个图形看成一个矩阵
declare in i=1
declare in j=1
end=`expr $1 \* 2 - 1` #变量end为矩阵大小
for i in ` seq 1 $end `
do
str="" #变量str存储每一行的字符串
if [ $i -le $1 ] #先输出前半部分
then
for j in `seq 1 $end`
do
left=`expr $1 - $i`;rigth=`expr $1 + $i`
if [[ $j -le $left ]] || [[ $j -ge $right ]] #使用逻辑或
then
str=$str" "
else
str=$str"*"
fi
done
else #输出下半部分
for j in `seq 1 $end`
do
left=`expr $i - $1`;right=`expr 3 \* $1 - $i`
if [[ $j -le $left ]] || [[ $j -ge $right ]]
then
str=$str" "
else
str=$str"*"
fi
done
fi
echo "$str"
done
#执行:./image.sh 4
脚本执行结果如下:
知识点:1. 输出的变量中存在连续空格时,使用echo “$str”;而不是echo $str。后者输出只保留一个空格。2.使用逻辑关系或与非时,使用[[判断条件]]。
3. until循环语句:until 判断条件-do 循环体-done。因为until循环和while循环语句不同在于判断条件刚好相反。容易理解,但是又容易混,所以我自己就是只使用while循环。尽量不使用until,除非题目要求或者特殊情况下。当然一些大佬,为了显示自己擅长写shell,用until,但是和while一样。
这里只是简单的一个小例子。在终端输出1~10
#!/bin/bash
declare -i i=1
until test $i -gt 10
do
echo $i
i=$i+1
done