一、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