Linux命令:break,continue,while

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux命令: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..."


[[email protected] 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


[[email protected] 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"


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

[[email protected] 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


[[email protected] 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的主要内容,如果未能解决你的问题,请参考以下文章

linux 循环结构中的 break continue exit return区别

Linux Shell Break和Continue

Shell脚本break和continue命令

Linux系列:break和continue的使用方法

Shell break和continue命令

break,continue的使用