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

shell基础之三:循环语句for

时间:2015-09-14 12:27:52      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:bash

一、循环语句for

bash中的循环控制语句for,while,until

for循环语法1

       for 变量名 in 列表;do

          循环体

       done

运行特性:

   第一遍:将列表中的第一个元素赋值“变量名”定义的变量,而后执行完成循环体;

   第二遍:、、、直到元素遍历结束,循环退出 


列表的生成方式:

          1、直接列出  如: stu100 stu101 stu102  或{stu100,stu101,stu102}

          2、生成整数列表  如:{start_num..end_num} 例:{1..10} 特定格式,表示1到10

          3、使用文件名通配的机制生成列表

          4、使用命令生成

                    seq LAST

                    seq FIRST LAST

                    seq FIRST STEP LAST  

例:

[root@localhost ~]# seq 1 2 10
1
3
5
7
9
[root@localhost ~]#

2、创建10个用户user10-user19,密码同用户名,在/tmp/创建10个空文件file10-file19,把file10-file19属主属组改为user10-user19

[root@localhost script]# cat 5useradd.sh 
#/bin/bash
for i in {10..19} 
do
useradd user$i
touch /tmp/file$i
chown user$i:user$i /tmp/file$i
done
[root@localhost script]#

3、写一个脚本用file命令显示/var/log目录下每个文件的内容类型。

[root@xxj shell]# cat 3.sh
#!/bin/bash
for i in /var/log/*
do
file $i 
done

6、显示/etc/passwd中第3,7和11个用户的用户名 和ID号

[root@xxj shell]# cat 6.sh
#!/bin/bash
for i in {3,7,11}
do
head -$i /etc/passwd|tail -1|cut -d: -f1,3
done
[root@xxj shell]# bash 6.sh
daemon:2
shutdown:6
operator:11

7、显示/etc/passwd文件中位于偶数行的用户的用户名

[root@localhost script]# cat 4useradd.sh 
#/bin/bash
lines=$(cat /etc/passwd|wc -l)
for i in $(seq 2 2 $lines)
do
head -n $i /etc/passwd|tail -1|cut -d: -f1
done
[root@localhost script]# bash 4useradd.sh
bin
adm
sync
halt
uucp
games
ftp
dbus
rpc
rpcuser
haldaemon
saslauth
sshd
oprofile
xj
stu101
stu105
stu107
stu111
stu120
stu122
stu131
usersb
usersib
userx111
userj333x111
[root@localhost script]# bash 4useradd.sh|wc -l
26
[root@localhost script]#

练习:

   1、 计算100以内所有正整数之和

[root@xxj shell]# cat 8.sh
#!/bin/bash
sum=o
for i in {1..100}
do
  sum=$[$sum+$i]
done
  echo $sum
[root@xxj shell]# bash 8.sh
5050

2、分别计算1000以内所有偶数之和和奇数之和

[root@xxj shell]# bash 9.sh
The sum is 2500
The sum is 2550
[root@xxj shell]# cat 9.sh
#!/bin/bash
y=0
for i in $(seq 1 2 100)
do
  y=$[$y+$i]
done
echo "The sum is $y"

#################
for a in $(seq 2 2 100)
do 
  b=$[$b+$a]
done
echo "The sum is $b"


shell基础之三:循环语句for

标签:bash

原文地址:http://xiexiaojun.blog.51cto.com/2305291/1694441

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