Board logo

标题: shell简介入门之bash编程之流程控制(1) [打印本页]

作者: samwalton    时间: 2014-2-27 16:43     标题: shell简介入门之bash编程之流程控制(1)

在介绍流程控制之前我们先来看看twst命令。test命令的参数是条件判式,当为真时则传回非零
  值,而条件为假时则传回零。在所有的流程控制都必须用到test命令来判断真假。另外一种方法
  是使用中括号[],一般都是用中括号居多。测试的种类有:
  A::字符串测试
  string1 = string 2 两字符串是否相等
  string1 != string2 两字符串是否不等
  string  字符串是否是空的
  -z string 字符串长度是否为0
  -n string 字符串长度是否非0
  B::整数测试
  -eq 等于
  -ne  不等
  -lt 小于
  -gt  大于
  -le 小于或等于
  -ge 大于或等于
  C::文件测试
  -b 区块文件
  -c 字符文件 
  -d 目录
  -f 一般文件
  -r 可读
  -w 可写
  -x 可执行
  -k 设定了限定位
  -g 设定了组位
  -u 设定了use id
  -p 管线
  -s 文件大小非0
  以下介绍各种流程控制
  A::
  if then
  语法如下:
  if (condition)
   then
   then-commands
  fi
  condition是一个test命令。往的一所介绍的各种流程中的conditon都是test命令。
  例如:
  test4.sh
  --------------------------------------------------
  #!/bin/bash
  if(test $# !=0)
   then
   echo Arg11
  fi
  --------------------------------------------------
  $/test4.sh hello
  Arg1:hello
  $./test4.sh
  $
  B::
  if then else
  语法如下:
  if(confition)
   then
   then-commands
   else
   else-commands
  fi
  C::
  if then elif
  语法如下:
  if (conditon1)
   then
   commands1
  elif(condition2)
   then
   commands2
  else
   commands3
  fi
  例如:
  test5.sh
  -------------------------------------------------------------
  #!/bin/bash
  echo `word 1:`
  read word1
  echo `word 2:`
  read word2
  echo `word 3:`
  read word3
  if(test "$word1" = "$word2" -a "$word2" = "$word3")
   then
   echo `match:words 1,2 & 3`
  elif(test "$word1" = "$word2")
   then
   echo `match:word 1 & 2`
  elif(test "$word1" = "$word3")
   then
   echo `match:words 1 & 3`
  elif(test "$word2"="$word3")
   then
   echo `match:words 2 & 3`
  else
   echo `no match `
  ------------------------------------------------------
  $./test5.sh
  word 1:
  do
  word 2:
  do
  word 3:
  do
  match:words 1,2&3
  D::
  for in
  语法如下:
  for var in arg-list
   do
   commands
  done
  例如:
  test6.sh
  --------------------------------------------------
  #!/bin/bash
  for a in xx yy zz
   do
   echo $a
  done
  ---------------------------------------------------
  结果如下:
  xx
  yy
  zz
  E::
  语法如下
  for var
   do
   commands
  done
  例如
  test7.sh
  -------------------------------
  #!/bin/bash
  for a
   do
   echo $a
  done
  -----------------------
  $./test7.sh xx yy zz
  xx
  yy
  zz




欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) Powered by Discuz! 7.0.0