Linux之shell编程基本语句

来源:互联网 发布:php mvc的实现 编辑:程序博客网 时间:2024/06/06 03:01

顺序结构:

顺序结构使用比较简单,可以依照程序中从上到下的顺序依次存放程序中的内容。这些内容可以是简单

的Linux命令,也可以其它的程序结构,比如判断结构或者循环结构。咱们举个例子来说明:

[cpp] view plain copy
 print?
  1. #! /bin/bash  
  2.  echo "-----------------the starting line of shell-----------------"  
  3.   
  4.  va=3  
  5.  vb=5  
  6.   
  7.  echo "value of va is:$va"  
  8.  echo "value of vb is:$vb"  
  9.    
  10. if [ $va -gt $va ]  
  11. then  
  12. >-------echo "the value of va is greater than vb"  
  13. else  
  14. >-------echo "the value of va is less than vb"  
  15. fi  
  16.   
  17. for var in a b c-  
  18. do  
  19. >-------echo "var=$var"  
  20. done  
  21.   
  22. echo "-----------------the ending line of shell-----------------"   

新建立一个名叫t1.sh的脚本文件,把上面的内容输入到文件中,保存后,给文件加上执行权限,然后在

终端中运行该文件,得到以下的结果:

-----------------the starting line of shell-----------------

value of va is:3

value of vb is:5

the value of va is less than vb

var=a

var=b

var=c

-----------------the ending line of shell-----------------



判断结构:

判断结构的程序块可以是顺序结果,或者嵌套判断结构,甚至是循环结构也可以放到里面。所以对程序

块的内容,不做太多的说明。咱们重点说一下判断结构中的条件。条件只能是Linux命令,因为判断结构

需要依据命令的执行结果才能继续运行。这里的命令可以是普通的Linux命令,但是用的最多的还是test命

令。看官莫急,咱们通过举例子来说明。

[cpp] view plain copy
 print?
  1.  #! /bin/bash  
  2.   echo "-----------------the starting line of shell-----------------"  
  3.   
  4.   if cd /usr/  
  5.   then  
  6.   >-------echo "the cd commond is running successfully"  
  7.   else  
  8.  >-------echo "the cd commond is not running successfully"  
  9.  fi  
  10.   
  11.  if [ -d "/usr/" ]                                                                          
  12.  then  
  13. >-------echo "the /usr/ is a directory"  
  14.  else  
  15. >-------echo "the /usr/ is not a directory"  
  16.  fi  
  17.   
  18.  echo "-----------------the ending line of shell-----------------"  
  

新建立一个名叫t2.sh的脚本文件,把上面的内容输入到文件中,保存后,给文件加上执行权限,然后在

终端中运行该文件,得到以下的结果:

-----------------the starting line of shell-----------------

the cd commond is running successfully

the /usr/ is a directory

-----------------the ending line of shell-----------------



0 0
原创粉丝点击