一、习题
1. 脚本编程:求200内的质数,并输出。
1 for((i=2;i<=200;i++))
2 do
3 flag=1
4 for((j=2;j<i;j++))
5 do
6 model=$[$i%$j]
7 if [ $model = 0 ];then
8 flag=0
9 break
10 fi
11 done
12 if [ $flag = 1 ];then
13 echo $i
14 fi
15 done
2. 编写shell脚本,循环打印这句话中字母数不大于5的单词:“It is no exception with the issue of examination.”
1 while [ 1=1 ]
2 do
3 for i in It is not exception with issue of examination
4 do
5 len=${#i}
6 if [ $len -le 6 ];then
7 echo $i
8 fi
9 done
10 done
3. 编写shell脚本,接收用户输入的数字来打印一个等腰三角形,例如: 输入 5,打印结果Please Enter a number:5
1 echo Please Enter a number:
2 read num
3
4 for((i=1;i<=$num;i++))
5 do
6 space=$num-$i
7 for((j=1;j<=$space;j++))
8 do
9 echo -e " \c"
10 done
11
12 star=$[$i*2-1]
13 for((j=1;j<=$star;j++))
14 do
15 echo -e "*\c"
16 done
17
18 echo
19 done
二、错误总结
1.缺失空格错误
- 在[ ]的附近要留空格
- 在=两边要留空格
- if后面留一个空格
- while条件 [ ] 两侧留空格
2.新增知识点
- 读取单词长度 len=${#i}
- for i in It is not exception with issue of examination 遍历每一个单词
3.常犯错误
- Bad for loop variable、illege number 使用bash e1.sh执行脚本
- 出现非整数错误 参与比较的数据的格式错误
- for循环的使用要加 (( ))
4.注意用法
-
for循环 do done 成对使用
-
echo用法
1.每次使用echo会自动换行
2.echo -e " \c" 打印不换行 -
赋值时,直接使用i=1
-
使用$符号
1.打印变量 echo $name
2.参与运算 $[ $ i% $ j ] star=$[ $ i*2-1] space=$[ $ num-$i]
3.进行判断 [ $model =0 ] -
break在case中需要;;