文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>shell语法之四-----控制结构

shell语法之四-----控制结构

时间:2010-11-09  来源:FreedomXura

1.if语句 格式:

if condition
then
  stat1
else
  stat2
fi

例子:vi if.sh

1 #!/bin/sh

  2
  3 echo "Is it morning?Please answer yes or no"
  4 read timeofday
  5
  6 if [ "$timeofday" = "yes" ];then
  7 echo "Good morning!"
  8 elif [ "$timeofday" = "no" ];then
  9 echo "Good afternoon!"
 10 else
 11 echo "Sorry,$timeofday not recognized.Enter yes or no"
 12 exit 1
 13 fi
 14
 15 exit 0



2.for语句 格式:

for variables in values
do
  stat1
done

例子:vi for.sh

1 #!/bin/bash

  2
  3 for variable in value1 value2 value3
  4 do
  5 echo "$variable"
  6 done
  7
  8 for file in "$(ls ./*.sh)";do
  9 echo $file
 10 done
 11
 12 exit 0



3.while语句 格式:

while condition do
 stat1
done

例子:vi while.sh

1 #!/bin/sh

  2
  3 echo "Enter password"
  4 read trythis
  5
  6 while [ "$trythis" != "mxh" ];do
  7 echo "sorry,try again!"
  8 read trythis
  9 done
 10
 11 exit 0

运行效果 :
4.until语句 格式:

until condition
do
 statements
done

例子:vi until.sh

1 #!/bin/sh

  2
  3 until who | grep "$1" > /dev/null
  4 do
  5 sleep 60
  6 done
  7
  8 #now ring the bell and announce the expected user.

  9
 10 echo "****$1 has just logged in ****"
 11
 12 exit 0

运行效果:
5.case语句 格式:

case variable in
 pattern [ | pattern] …) statements;;
 pattern [ | pattern] …) statements;;
esac

例子:vi case.sh

  1 #!/bin/bash

  2
  3 echo "Is it morning?Please answer yes or no!"
  4 read timeofday
  5
  6 case "$timeofday" in
  7 yes) echo "Good morning";;
  8 no) echo "Good Afternoon";;
  9 y) echo "Goog morning";;
 10 n) echo "Goog Afternoon";;
 11 *) echo "Sorry,answer yes or no";
 12 esac
 13
 14 case "$timeofday" in
 15 yes | YES | Yes | Y | y ) echo "Good morning";;
 16 no | NO | n | N ) echo "Good Afternoon";;
 17 *) echo "Sorry,answer yes or no";;
 18 esac
 19
 20 exit 0

运行效果:

6.and语句 格式:

sta1 && sta2 && sta3 && ...

从左到右顺序执行每条命令,如果上一条命令返回的是true,下一条命令才会被执行.符号&&的作用是检查前一条命令的返回值.

例子:vi and.sh

1 #!/bin/sh

  2
  3 touch file_one
  4 rm -f file_two
  5
  6 if [ -f file_one ] && echo "hello"&&[ -f file_two ] && echo "there"
  7 then
  8 echo "in if"
  9 else
 10 echo "in else"
 11 fi
 12
 13 exit 0


7.or语句 格式 :

stat1 || stat2 || stat3 || ...

执行这一些列指令,直到有一条命令成功为止,下一条指令将不被执行.
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载