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

shell 循环语句应用实例

时间:2017-01-05 18:52:21      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:shell 循环语句 for语句 while语句

1 for语句

语法格式

for 变量 in 值(或者循环条件)

do 

命令

done

给多个用户发送邮件

#!/bin/bash

domain=163.com

for user in tom hom jem

do 

mail -s "happy new year" $user@$domain < /var/log/messages

done

打印9*9的乘法口诀

#!/bin/bash

for i in {1..9}

do

    for ((j=1,j<=i,j++))

    do

        printf "%-8s" $j*$i=$((j*i))

    done

    echo

done


2 while 语句


语法格式

while 条件 do 命令 done

while read -r line  do 命令 done < file


批量添加20个用户,用户名userN,N为1到20数字

#!/bin/bash

u=1

while [ $u -le 20 ]

do

useradd user${ $u }

u=$((u+1))

done

按行读取打印网卡配置文件

#!/bin/bash

FILE=/etc/sysconfig/network-scripts/ifcfg-eth0

while read -r line

do

echo $line

done < $FILE


3 until语句

语法格式

until 条件 do 命令 done

批量删除用户,用户名userN,N为1到20数字

#!/bin/bash

u=20

until [ $u -eq 0 ]

do

userdel user${ $u }

u=$((u-1))

done


4 select语句

用select生成询问菜单

#!/bin/bash

echo "where are you"

select var in "shenzhen" "guangzhou" "meiguo" "xianggang"

    do

break

    done

echo "you are from $var"


5 控制语句

shift 将位置参数左移一位,也就是说执行shift后,$2变成$1,

countinue 中断当前循环,进入下一个循环

break 结束整个循环

exit 结束脚本的运行




本文出自 “实用Linux知识技能分享” 博客,请务必保留此出处http://superleedo.blog.51cto.com/12164670/1889347

shell 循环语句应用实例

标签:shell 循环语句 for语句 while语句

原文地址:http://superleedo.blog.51cto.com/12164670/1889347

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