shell脚本编程之循环控制结构

前端之家收集整理的这篇文章主要介绍了shell脚本编程之循环控制结构前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

循环控制之for循环

语法结构1

for Variable in List
do
commands
done

语法结构2

for Variable in List;do
commands
done

这个List可以为列表、变量、命令 等等

for循环 事先提供一个元素列表,而后,使用变量去遍历此元素列表,每访问一个元素,就执行一次循环体,直到元素访问完毕


1、for循环中的List为列表

eg1: 显示/etc/inittab,/etc/rc.d/rc.sysinit,/etc/fstab三个文件各有多少行;

#!/bin/bashforFile in/etc/inittab/etc/rc.d/rc.sysinit /etc/fstab;doRow=`wc-l $File | cut-d' '-f1`echo"$File has: $Row rows"done

运行结果 


2、for循环中的List为变量

eg2:显示当前ID大于500的用户用户名和id;

#!/bin/bashuseradduser1useradduser2useradduser3 #新建几个用户便于测试结果 Id=`cat/etc/passwd| awk-F: '{print $3}'`forVar in$Id;doif[ $Var -ge500 ];thenUser=`grep"$Var\>"/etc/passwd| cut-d: -f1`echo"$User uid is $Var"fidone

运行结果

3、for循环中的List为命令

eg3:显示当前shell为bash的用户用户名和shell。

显示结果为 Bash user:root,/bin/bash

分析:先通过以bash结尾的shell来确定用户,然后把这些用户一个一个的输出

#!/bin/bashforVar in`grep"bash\>"/etc/passwd| cut-d: -f7`;doUser=`grep"$Var"/etc/passwd|cut-d: -f1`doneShell=`grep"bash\>"/etc/passwd|cut-d: -f7 |uniq`forname in$User;doecho"Bash user:$name,$Shell"done

运行结果


4、for循环中的List为一连串的数字

eg4:分别计算1-100以内偶数(Even number)的和,奇数(Odd number)的和.

分析:当一个数与2取余用算时,为1则表示该数为奇数,反之为偶数。

#!/bin/bashEvenSum=0OddSum=0forI in`seq1 100`;doif[ $[$I%2] -eq1 ]; thenOddSum=$[$OddSum+$I]elseEvenSum=$[$EvenSum+$I]fidoneecho"EvenSum: $EvenSum."echo"OddSUm: $OddSum."

运行结果


5、C语言格式的for循环

eg5:添加用户从user520添加到user530,且密码与用户名一样。

#!/bin/bashfor((i=520;i<=530;i++));douseradduser$iecho"Add user$i."echouser$i | passwd-stdin user$i &>/dev/nulldone

运行结果:(可以切换一个用户试试密码是否和用户名一样)


其他循环的格式如下,所有这些循环熟练掌握一种循环即可。

while循环命令的格式

while test command
do
other command
done

until循环的命令格式

until test command
do
other command
done

一个脚本的面试题,各位博友可以把您的答案回复在下面(大家一起交流)

通过传递一个参数,来显示当前系统上所有默认shell为bash的用户和默认shell为/sbin/nologin的用户,并统计各类shell下的用户总数。

运行如 bash eg.sh bash则显示结果如下

BASH,3users,they are:
root,redhat,gentoo,

运行如 bash eg.sh nologin则显示结果如下

NOLOGIN,2users,they are:
bin,ftp,

猜你在找的Shell相关文章