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

Linux命令:break,continue,while

时间:2016-11-14 16:00:02      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:break   continue   while   


一、while的特殊用法一一直循环,永不退出

while :;do

  ...

done


#!/bin/bash
# showfile.sh
while : ; do
  read -p "Files path:" FILEPATH
  [ $FILEPATH == ‘quit‘ ] && break
  if [ -e $FILEPATH ];then
    echo "$FILEPATH exists."
  else
    echo "No $FILEPATH."
  fi
done
echo "Quit..."


[root@localhost yum.repos.d]# ./showfile.sh
Files path:/etc
/etc exists.
Files path:/etcc/
No /etcc/.
Files path:/yum/VT
/yum/VT exists.
Files path:quit
Quit...


二、while的特殊用法二:       将文本逐行处理

while read LINE; do

 ...

done < /PATH/TO/SOMEFILE


#!/bin/bash
# showfile.sh
FILE=/etc/passwd
let I=1
while read LINE;do
  [ `echo $LINE |awk -F : ‘{print $NF}‘` == ‘/bin/bash‘ ] && echo $LINE |awk -F : ‘{print $1}‘ && let I++
  [ $I -gt 2 ] && break
done <$FILE


[root@localhost yum.repos.d]# ./showuser.sh
root
./showuser.sh: line 6: [: ==: unary operator expected
oracle


区别continue与break运行机制:

#!/bin/bash
# odd.sh
let SUM=0
let I=0

read -p "keyin I:" I2
read -p "keyin SUM:" SUM2

while [ $I -lt $I2 ];do
  let I++
  if [ $[$I%2] -eq 1 ]; then
    continue    # 结束本轮或本次循环
  fi
  if [ $SUM -ge $SUM2 ] ;then
    break       # 提前退出此while循环
  fi
  let SUM+=$I
done

echo "SUM=$SUM; I=$I"


[root@localhost yum.repos.d]# ./odd.sh
keyin I:100
keyin SUM:2000
SUM=2070; I=92
[root@localhost yum.repos.d]# ./odd.sh
keyin I:100
keyin SUM:200
SUM=210; I=30

[root@localhost yum.repos.d]# ./odd.sh
keyin I:1000
keyin SUM:20000
SUM=20022; I=284




三、自动查看bash脚本是否有问题,且显示错误后进入该脚本修改

#!/bin/bash
# syntax.sh
until bash -n $1 &> /dev/null; do
  read -p "Syntax error,[Q|q] to quit,others for editing: " CHOICE
  case $CHOICE in
  q|Q)
    echo "Something wrong,quiting..."
    exit 5;;
  *)
    bash -n $1
    sleep 5
    vim + $1;;
  esac
done


[root@localhost yum.repos.d]# ./syntax.sh hello.sh
Syntax error,[Q|q] to quit,others for editing:
hello.sh: line 2: syntax error near unexpected token `;‘
hello.sh: line 2: `while ;do‘
Syntax error,[Q|q] to quit,others for editing:
hello.sh: line 2: syntax error near unexpected token `;‘
hello.sh: line 2: `while ;do‘

Linux命令:break,continue,while

标签:break   continue   while   

原文地址:http://wangfx.blog.51cto.com/1697877/1872658

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