标签:while
while 测试条件
do
语句1
语句2
done
测试条件:条件满足就循环,直到条件不满足就退出循环
while循环如何退出?在循环体中改变测试条件相应的变量值
补充:算术运算符
sum=$[$sum+$i] = sum+=$i
-=
*=
sum+=1 = let sum++
sum--
sam=3
while [ $sam - le 5 ]
do
let sam++
done
例子:用户随机输入一个数值,就循环几次echo "test" >> /tmp/123
#!/bin/bash a=1 read -p "Please enter a number:" sam while [ $a -le $sam ] do echo "test" >> /tmp/123 let a++ done
例子2:当前系统所有用户,ID号为偶数就输出用户名和shell
#!/bin/bash file=/etc/passwd while read line read 会自动将$file这个文件中的每一行,将读取的每一行的值付给$line do id=$(echo $line | cut -d: -f3) if [ $[$id%2] -eq 0 ] $id除于2取余等于0 就执行 then username=$(echo "$line" |cut -d: -f1) shell=$(echo "$line" | cut -d: -f7) echo -e "UserName:$username\nShell:$shell\n" fi done < $file
列子:将用户输入的字符转换成大写,字符quit退出脚本
#!/bin/bash
read -p "A string:" string while [ "$string" != "quit" ] 如果用户输入的不是quit就会一直循环直到字符串是quit do echo "$strin" | tr "a-z" "A-Z" read -p "New String [ quit for exit] :" string done
------------------------------------------------------------------------------------
until循环 测试条件
do
语句1
语句2
done
条件不满足循环,直到满足就退出循环
列子:将用户输入的字符转换成大写,字符quit退出脚本
#!/bin/bash
read -p "A string:" string
until [ "$string" == "quit" ] 如果用户输入的是a.$string=quit 条件不满足就继续循环,知道$string=quit条件满足时退出
do
echo "$strin" | tr "a-z" "A-Z"
read -p "New String [ quit for exit] :" string
done
例子2:每隔5秒查看hadoop用户是否登录,显示登录并退出;否则显示当前时间,并输出hadoop尚未登录
#!/bin/bash until who | grep "^hadoop" &> /dev/null do echo "$(date) hadoop not login" sleep 5done dong echo "hadoop login" exit 0
例子3:显示如下菜单,让用户选择,并输出相关信息,当用户选择完成,显示相应信息,不退出,让用户重新选择,直到输入quit退出
cat << EOF
d|D) show disk usages
m|M) show memory usages
s|S) show swap usages
*)quit
EOF
---------------------------------------
#!/bin/bash cat << EOF d|D) show disk usages m|M) show memory usages s|S) show swap usages *)quit EOFread -p "Please Input Device :" usages until [ "$usages" == "quit" ] do case $usages in d|D) df -h read -p "Please Input Device :" usages ;; m|M) free -m | head -2 read -p "Please Input Device :" usages ;; s|S) free -m | tail -1 read -p "Please Input Device :" usages ;; *) echo "Input error" exit 7 esacdone ;; esac dong
本文出自 “悬剑” 博客,请务必保留此出处http://sublime.blog.51cto.com/8856101/1538989
Shell脚本-----while循环和until循环,布布扣,bubuko.com
标签:while
原文地址:http://sublime.blog.51cto.com/8856101/1538989