linux复习1(shell脚本)

一、习题

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.缺失空格错误

  1. 在[ ]的附近要留空格
  2. 在=两边要留空格
  3. if后面留一个空格
  4. while条件 [ ] 两侧留空格

2.新增知识点

  1. 读取单词长度 len=${#i}
  2. for i in It is not exception with issue of examination 遍历每一个单词

3.常犯错误

  1. Bad for loop variable、illege number 使用bash e1.sh执行脚本
  2. 出现非整数错误 参与比较的数据的格式错误
  3. for循环的使用要加 (( ))

4.注意用法

  1. for循环 do done 成对使用

  2. echo用法
    1.每次使用echo会自动换行
    2.echo -e " \c" 打印不换行

  3. 赋值时,直接使用i=1

  4. 使用$符号
    1.打印变量 echo $name
    2.参与运算 $[ $ i% $ j ] star=$[ $ i*2-1] space=$[ $ num-$i]
    3.进行判断 [ $model =0 ]

  5. break在case中需要;;

发布了122 篇原创文章 · 获赞 221 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/jjsjsjjdj/article/details/103463054