码迷,mamicode.com
首页 > 系统相关 > 详细

Shell编程<1>---控制语句

时间:2014-12-08 21:25:16      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:shell

最近在看 Linux 程序设计,准备写成一个系列。把每天学到的记录下来。 以实际的例子为主。

一、条件语句

if 语句

语法

#用法 1 
if condition1
then
  statement
elif condition2
then
  statement
fi
#用法 2 
if condition1; then
  statement
elif condition2; then
  statement
else
  statement
fi

例子

  • case1:
    #!/bin/sh 
    echo "Is it moring? Please answer yes or no"
    read timeofday
    if [ "$timeofday" = "yes" ]; then
      echo "Good morning"
    elif [ "$timeofday" = "no" ]; then
      echo "Good afternoon"
    else
      echo "sorry, $timeofday not recognized. Enter yes or no"
      exit 1
    fi
    exit 0

case 语句

  • case1:
    echo "Is it morning? Please input yes or no?"
    read timeofday
    case $timeofday in
      yes) echo "Good morning";; #双分号 
      no) echo "Good afternoon";;
      y) echo "Good morning";;
      n) echo "Good afternoon";;
      *) echo "Sorry, answer not recognized";;
    esac
  • case2: 合并匹配模式
    echo "Is it morning? Please input yes or no?"
    read timeofday
    case $timeofday in
      yes | y | Yes | YES) echo "Good morning";; #双分号 
      n* | N*) echo "Good afternoon";;
      *) echo "Sorry, answer not recognized";;
    esac
  • case3: 多条语句
    read timeofday
    case $timeofday in
    yes | y | Yes | YES)
    echo "Good morning"
    echo "Up bright and early in the morning"
    ;; #双分号 
    [nN]*)
    echo "Good afternoon"
    ;;
    *)
    echo "Sorry, answer not recognized"
    exit 1
    ;;
    esac
    exit 0

二、循环语句

for 语句

  • case1: 固定字符串的for循环
    for file in bar fud 43; do
      echo $file
    done
  • case2: 使用通配符的for循环
    for file in $(ls f*.sh); do
      echo $file
    done
    输出:
    bar
    fud
    43
  • case3: 以 test1.txt test2.txt ...运行 a.out
    for ((i=0; i<200; i++)); do #必须有两个括号 
     ./a.out < test$i.txt
    done
    +case4: 将当前目录下的所有的.txt改名为 .gif
    for file in *.gif
    do
    mv $file  ${file%%gif}txt  //${file%%gif}表示从尾部开始删除与gif匹配的最长部分
    done

while 语句

  • case1: 密码输入程序
    echo "Enter Password"
    read trythis
    while [ "$trythis" !"secret" ]; do
      echo "Sorry, try again"
      read trythis
    done
    echo "Congrats, password correct"

until 语句

与while 相反,当条件不满足时一直运行,直到条件为真

  • case1:
    read trythis
    until [ $trythis = "secret" ]; do
      echo "Sorry, try again"
      read trythis
    done

二、其他

And 和 Or

statement && statement
statement || statement

语句块

statement && {
  statement1
  statement2
  statement3
  ...
}

Shell编程<1>---控制语句

标签:shell

原文地址:http://blog.csdn.net/shoulinjun/article/details/41808985

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!