while命令简介:
while循环:适用于循环次数未知的场景,要有退出条件,否则就成为死循环。
1.命令格式:
语法:
while CONDITION; do
statement
...
done
2.命令功能:
while循环:适用于循环次数未知的场景,要有退出条件,否则就成为死循环。
3.命令参数:
while CONDITION; do condition:进入循环的条件
statement
...
done
4.命令实例:
1、计算100以内整数和
[[email protected] test]# vim while100.sh
#!/bin/bash
#program:
#练习使用while循环计算1到100正整数的和
#history donggen 2016-11-02-21:21
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bash
export PATH
declare -i I=1
declare -i SUM=0
while [ $I -le 100 ]; do
let SUM+=$I
let I++
done
echo "$SUM"
[[email protected] test]# chmod +x while100.sh
[[email protected] test]# ./while100.sh
5050 从1到100的正整数和为5050
[[email protected] test]#
2、如果提示用户输入字符,如果不是quit就把小写字母全部变成大写字母,
如果是quit则退出脚本。
[[email protected] test]# vim whilequit.sh
#!/bin/bash
#program:
#如果输入的不是quit则把小写字母全部换成大写字母,quit退出循环
#history donggen 2016-11-02-21:31
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bash
export PATH
read -p "Input something:" SCRIPT
while [ $SCRIPT != "quit" ]; do
echo "$SCRIPT" | tr ‘a-z‘ ‘A-Z‘
read -p "Input something:" SCRIPT
done
[[email protected] test]# chmod +x whilequit.sh
[[email protected] test]# ./whilequit.sh
Input something:abc
ABC
Input something:eroqe
EROQE
Input something:quit
[[email protected] test]#
3、写一个脚本,查看一个用户是否登录,如果没有登录继续查看,如果登录则提
示用户已经登录并退出循环。
[[email protected] test]# vim whiledonggen.sh
#!/bin/bash
#program:
#查看用户是否登录
#history donggen 2016-11-02-21:45
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bash
export PATH
USERNUM=donggen
who | grep "$USERNUM" &> /dev/null
NUM=$?
while [ $NUM -ne 0 ]; do
echo "$USERNUM is not login."
sleep 3
who | grep "$USERNUM" &> /dev/null
NUM=$?
done
echo "the $USERNUM is login."
[[email protected] test]# chmod +x whiledonggen.sh
[[email protected] test]# ./whiledonggen.sh
donggen is not login. donggen 用户没有登录时一直提示没有登录
donggen is not login.
donggen is not login.
donggen is not login.
the donggen is login. donggen用户登录后提示登录并退出循环。
[[email protected] test]#