生物信息学缘起——linux篇(六)for和while循环

Linux中for和while循环语句介绍

一、for循环语句

在linux中,for循环语句的逻辑和使用方法与其他编程语言类似,允许你创建一个遍历一系列值的循环,每次迭代都使用其中一个值来执行已定义好的一组命令。

for var in list
    do
    commands
done

for命令用空格来划分list中的每个值。如果在单独的数据值中有空格,就必须用双引号将这些值圈起来。

#!/bin/bash
# an example of how to properly define values
for test in Nevada "New Hampshire" "New Mexico" "New York"
    do
    echo "Now going to $test"
done

你也可以更改环境变量IFS(内部字段分隔符),重新规定分隔符:

$ cat states
Alabama
Alaska
Arizona
Arkansas
Colorado
Connecticut
Delaware
Florida
Georgia

#!/bin/bash
# reading values from a file
file="states"
IFS=$'\n'
for state in $(cat $file)
    do
    echo "Visit beautiful $state"
done

你也可以像C语言那样写计数器迭代:

$ cat test8
#!/bin/bash
# testing the C-style for loop
for (( i=1; i <= 10; i++ ))
    do
    echo "The next number is $i"
done
$ ./test8
The next number is 1
The next number is 2
The next number is 3
The next number is 4
The next number is 5
The next number is 6
The next number is 7
The next number is 8
The next number is 9
The next number is 10

二、while循环语句

在linux中,while命令的格式是:

while test command
    do
    other commands
done

while命令的关键在于所指定的test command的退出状态码必须随着循环中运行的命令而改变。如果退出状态码不发生变化, while循环就将一直不停地进行下去。

最常见的test command的用法是用方括号来检查循环命令中用到的shell变量的值。

#!/bin/bash
# while command test
    var1=10
    while [ $var1 -gt 0 ]
        do
        echo $var1
        var1=$[ $var1 - 1 ]
done

$ ./test10
10
9
8
7
6
5
4
3
2
1
$

参考资料:《linux命令行与shell脚本编程大全.第三版》

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值