Bash中的循环语句有以下三种格式:
第一种形式:
for variable_name in [ expression ] ; do
statements
done
第二种形式:
while [ expression ] ; do
statements
done
第三种形式:
until [ expression ]; do
statements
done
第一种形式的示例如下:
#!/bin/bash
#traverse the files contained in current directory
for i in $(ls); do
echo "Item:$i"
done
也可以使用`ls`,例如:
#!/bin/bash
#traverse the files contained in current directory
for i in `ls`; do
echo "Item: $i"
done
第二种形式的示例
#!/bin/bash
#counting from a to b with step length equaling to 1
a=2
b=10
while [ $a -lt $b ]; do
echo $a
let a=a+1
done;
第三种形式的示例:
#!/bin/bash
#counting from number a to number b with step length equaling to 1
a=1
b=10
until [ $a -gt $b ]; do
echo $a
let a=a+1
done
可以使用sed写出类似于python那样的循环语句,例如:
#!/bin/bash
for i in `seq 1 1 10` ; do
echo i=$i
done