过程式编程语言代码执行顺序

顺序执行 逐条逐条执行

选择执行 代码有一个分支,条件满足是才会执行;两个或以上的分支只会执行其中一个分支

循环执行 代码片段(循环体)执行0,1多个来回



选择执行是指代码有一个分支,条件满足时才会执行

选择执行:

  1.if语句

  

  单分支if语句

if 测试条件;then

代码分支

fi

[root@localhost testdir]# vim if1.sh
#!/bin/bash
#snowbamboo
#2016.08.19
#单分支if语句脚本
if [ -e $1 ]; then
        echo "The file $1 exists"
fi
#$1 为位置变量,表示为第几个参数 (有关变量请参考 8/1837434) 
[root@localhost testdir]# bash if1.sh q
The file q exists

  双分支语句

if 测试条件;then

条件为真时执行代码分支

else 

条件为假时执行的代码分支

fi

[root@localhost testdir]# vim if2.sh
#!/bin/bash
#snowbamboo
#2016.08.19
#双分支if语句脚本
if [ -e $1 ]; then
        echo "The file $1 exists"
else echo "then file $1 does not exist"
fi
#$1 为位置变量,表示为第几个参数 
[root@localhost testdir]# bash if2.sh q
The file q exists
[root@localhost testdir]# bash if2.sh qq
then file qq does not exist


   多分支语句

if 测试条件;then

条件为真时执行代码分支

elif 测试条件;then

条件为真时执行代码分支

elif 测试条件;then

else 

以上条件都不为真执行

fi

逐条进行判断,分支只会执行其中一个,只要第一个条件满足就执行,并退出。

[root@localhost bin]# bash test.sh file11 
Input is not a file
[root@localhost bin]# bash test.sh test
test is file good!
[root@localhost bin]# bash test.sh test1/
test1/ is directory,please input a file


2.选择执行case语句


case 变量名 in

值1)

执行语句1

;;

值2)

执行语句2

;;

值3)

执行语句3

;;

esac

结构更加明晰,当第一次满足值的条件后退出。

#!/bin/bash
#
read -p "please input (yes |no) :" A
case $A in
[yY]|[yY][eE][Ss])
        echo "The user input a $A" 
         ;;
[nN]|[[nN][oO])
        echo  "The user input  a  $A"
  ;;
*)
        echo "The user input other message" ;;
esac
#用户输入yes或no,判断用户输入的是yes还是no