用途说明
在shell中用于循环。类似于其他编程语言中的for,但又有些不同。for循环是Bash中最常用的语法结构。 常用格式 格式一
for 变量
do
语句
done 格式二
for 变量 in 列表
do
语句
done 格式三
for ((变量=初始值; 条件判断; 变量变化))
do
语句
done 使用示例 示例一
Bash代码
for s in ac apropos at arp
do
echo $s
done
[root@jfht ~]# for s in ac apropos at arp
> do
> echo $s
> done
ac
apropos
at
arp
[root@jfht ~]# 示例二
Bash代码
for f in *
do
echo $f
done
[root@jfht ~]# for f in *
> do
> echo $f
> done
anaconda-ks.cfg
bak181
hlx
install.log
install.log.syslog
job.sh
job.txt
mbox
mini
setup
temp
vsftpd-2.0.5-16.el5.i386.rpm
vsftpd.conf
work191
[root@jfht ~]# 示例三
Bash代码
ls >ls.txt
for s in $(cat ls.txt)
do
echo $s
done
[root@jfht ~]# ls >ls.txt
[root@jfht ~]# for s in $(cat ls.txt)
>
> do
>
> echo $s
>
> done
anaconda-ks.cfg
bak181
hlx
install.log
install.log.syslog
job.sh
job.txt
ls.txt
mbox
mini
setup
temp
vsftpd-2.0.5-16.el5.i386.rpm
vsftpd.conf
work191
[root@jfht ~]# 示例四
Bash代码
print_args()
{
for arg in "$@"
do
echo $arg
done
}
print_args 1 2 3 4
print_args "this is a test"
"color: #000000;">print_args this is a test
[root@smsgw root]# print_args()
> {
> for arg in "$@"
> do
> echo $arg
> done
> }
[root@smsgw root]# print_args 1 2 3 4
1
2
3
4
[root@smsgw root]# print_args "this is a test"
this is a test
[root@smsgw root]# print_args this is a test
this
is
a
test 示例五
Bash代码
[root@smsgw root]# bash --version
GNU bash, version 2.05b.0(1)-release (i386-redhat-linux-gnu)
Copyright (C) 2002 Free Software Foundation, Inc.
[root@smsgw root]# for i in {1..5}
> do
> echo "Welcome $i times"
> done
Welcome {1..5} times
[root@smsgw root]#
换个较高版本的Linux。
[root@jfht ~]# bash --version
GNU bash, version 3.2.25(1)-release (i686-redhat-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.
[root@jfht ~]# for i in {1..5}
> do
> echo "Welcome $i times"
> done
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times
[root@jfht ~]# 示例八 Bash v4.0+
Bash代码
echo "Bash version ${BASH_VERSION}..."
for i in {0..10..2}
do
echo "Welcome $i times"
done
[root@smsgw root]# echo "Bash version ${BASH_VERSION}..."
Bash version 2.05b.0(1)-release...
[root@smsgw root]# for i in {0..10..2}
> do
> echo "Welcome $i times"
> done
Welcome {0..10..2} times
[root@smsgw root]#
换个较高版本的Linux。
[root@jfht ~]# echo "Bash version ${BASH_VERSION}..."
Bash version 3.2.25(1)-release...
[root@jfht ~]# for i in {0..10..2}
> do
> echo "Welcome $i times"
> done
Welcome {0..10..2} times
[root@jfht ~]#
传说Bash4.0可以支持这种语法。
Bash version 4.0.33(0)-release...
Welcome 0 times
Welcome 2 times
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times