shell for ..in ..


for...in...循环格式:
for 变量 in 列表
do
    command1
    command2
    ...
    commandN
done
列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。

示例1
#!/bin/bash
databases=`mysql -udev -p123456a?  -h10.41.2.200  -P3306 -e "show databases"`
echo  ${databases}
echo '--------------------'
for database in ${databases}
do
    echo "database:${database}"
done
echo '--------------------'

输出结果:
Database information_schema consoledb iop_dev iop_integ mysql performance_schema service_css test test_service
--------------------
database:Database
database:information_schema
database:consoledb
database:iop_dev
database:iop_integ
database:mysql
database:performance_schema
database:service_css
database:test
database:test_service
--------------------

示例2
显示主目录下以 .bash 开头的文件:
for FILE in $HOME/.bash*
do
   echo $FILE
done
echo '--------------------'

输出结果
/root/.bash_history
/root/.bash_logout
/root/.bash_profile
/root/.bashrc
--------------------

示例3
for str in 'This is a string'
do
    echo $str
done
echo '--------------------'

for str in "This is a string"
do
    echo $str
done
echo '--------------------'

for str in This is a string
do
    echo $str
done
echo '--------------------'

输出结果:
This is a string
--------------------
This is a string
--------------------
This
is
a
string
--------------------

猜你喜欢

转载自huangqiqing123.iteye.com/blog/2266162