您的位置:首页 > 运维架构 > Shell

shell 编程 for 循环详解及应用实例

2018-02-24 15:21 387 查看
与其他编程语言类似,Shell支持for循环。
for循环一般格式为:
for 变量 in 列表
do
    command1
    command2
    ...
    commandN
done
列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。
in 列表是可选的,如果不用它,for 循环使用命令行的位置参数。

例如,顺序输出当前列表中的数字:
for loop in 1 2 3 4 5
do
echo "The value is: $loop"
done
运行结果:
The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5

顺序输出字符串中的字符:
for str in 'This is a string'
do
echo $str
done
运行结果:
This is a string

显示主目录下以 .bash 开头的文件:
#!/bin/bash
for FILE in $HOME/.bash*
do
echo $FILE
done
运行结果:
/root/.bash_history
/root/.bash_logout
/root/.bash_profile
/root/.bashrc

应用实例:

第一类:数字性循环

-----------------------------

for1-1.sh#!/bin/bash
for((i=1;i<=10;i++));
do
echo $(expr $i \* 3 + 1);
done expr命令可以实现数值运算、数值或字符串比较、字符串匹配、字符串提取、字符串长度计算等功能
\ 在这里表示转义  进行乘法运算 *
biao@ubuntu:~/test/shell_for$ ./test.sh 
4
7
10
13
16
19
22
25
28

31
-----------------------------

for1-2.sh
#!/bin/bash
for i in $(seq 1 10)
do
echo $(expr $i \* 3 + 1);
done -----------------------------
for1-3.sh
#!/bin/bash
for i in {1..10}
do
echo $(expr $i \* 3 + 1);
done -----------------------------
for1-4.sh#!/bin/bash
awk 'BEGIN{for(i=1; i<=10; i++) print i}'awk是一个强大的文本分析工具,awk经常用在文本文件的处理以及生成报表,主要进行流控制、数学运算、进程控制、内置的变量和函数、循环和判断

第二类:字符性循环
-----------------------------
for2-1.sh
#!/bin/bash
for i in `ls`;
do
echo $i is file name\! ;
done -----------------------------
运行结果为:
biao@ubuntu:~/test/shell_for$ touch a b c d
biao@ubuntu:~/test/shell_for$ ls
a  b  c  d  test.sh
biao@ubuntu:~/test/shell_for$ ./test.sh 
a is file name!
b is file name!
c is file name!
d is file name!
test.sh is file name!
biao@ubuntu:~/test/shell_for$ 

for2-2.sh#!/bin/bash
for i in $* ;
do
echo $i is input chart\! ;
done -----------------------------
for2-3.sh#!/bin/bash
for i in f1 f2 f3 ;
do
echo $i is appoint ;
done -----------------------------
for2-4.sh#!/bin/bash
list="rootfs usr data data2"
for i in $list;
do
echo $i is appoint ;
done 第三类:路径查找
-----------------------------
for3-1.sh#!/bin/bash
for file in ./*;
do
echo $file is file path \! ;
done
运行结果为:
biao@ubuntu:~/test/shell_for$ ls
a  b  c  d  test.sh
biao@ubuntu:~/test/shell_for$ ./test.sh 
./a is file path !
./b is file path !
./c is file path !
./d is file path !
./test.sh is file path !
biao@ubuntu:~/test/shell_for$ 

-----------------------------
for3-2.sh#!/bin/bash
for file in $(ls *.sh)
do
echo $file is file path \! ;
done
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell for 实例应用