Linux Shell编程002--控制流结构

一、if语句

       语句格式:

      if 条件

      then

      elif 条件

      then

      else

      fi

#!/bin/bash
echo -n "Please enter your name:"
read NAME
echo if  [ -z $NAME ]
echo $NAME
if [ -z $NAME ] || [ "$NAME"="" ];then
   echo "You didn't enter your name"
elif [ "$NAME"="root" ];then
   echo "root"
elif [ "$NAME"="shell" ]; then
   echo "shell"
else
   echo "Hello,$NAME"
fi

二、case语句为多选择语句,可以匹配一个值或者一个模式。

       case 值 in

         模式1)

扫描二维码关注公众号,回复: 2823490 查看本文章

              命令1

               ;;

         模式2)

              命令2

              ;;

       esac

#!/bin/bash
#case语句示例

echo "请输入A,B,C,中的任意一个字符:"
read grade
case $grade in
"A")
  echo "You enter A"
  ;;
"B")
  echo "You enter B"
  ;;
"C")
  echo "You enter C"
  ;;
*)
  echo "Bad input"
  exit
  ;;
esac

三、for语句

     for 变量名 in 列表

     do

         命令1

         命令n

     done

#!/bin/bash
#for语句的示例
for loop in 1,2,3,4,5
do
  echo $loop
done
for loop in "Hello World"
do
  echo $loop
done
for loop in `cat myfile`
do
  echo $loop
done

四、until语句

      until 条件

      do

          命令

      done

五、while语句

     while 条件

     do

     done

#!/bin/bash
echo "while语句示例"
echo "CTRL+D is means exit"
while echo "Hello world!" ;read name
do
   echo "yeah!!! $name"
done


# 循环读入文件内容
while read line
do
  echo $line
done < name.txt

六、continue :跳出本次循环继续下一次,break :跳出真个循环 break后面可接参数 n,表示跳出几层循环

#!/bin/bash
for num in 1 2 3 4 5 6 7 8 9
 do
  echo $num
 if [ "$num" = "3" ]
   then
     echo "Continue=="
     continue
   fi
   if [ "$num" = "7" ]
   then
      break
   fi
done

猜你喜欢

转载自blog.csdn.net/youran02100210/article/details/81778883