标题: 在 Linux 中,除了 do 命令,还有哪些常用的循环命令? [打印本页] 作者: linchen 时间: 2024-7-28 12:03 标题: 在 Linux 中,除了 do 命令,还有哪些常用的循环命令? [md]在Linux shell脚本中,除了使用 `do` 关键字的 `while` 和 `until` 循环外,还有以下几种常用的循环命令:
1. **for 循环**:
```bash
for variable in list
do
# Commands to execute for each item in list
done
```
2. **C-style for 循环**(在某些shell如bash中):
```bash
for (( initialization; condition; increment ))
do
# Commands to execute
done
```
3. **select 循环**(类似于C语言的switch-case):
```bash
select name [in list]
do
case $name in
pattern1 )
# Commands to execute if name matches pattern1
;;
pattern2 )
# Commands to execute if name matches pattern2
;;
* )
# Default commands to execute
;;
esac
done
```
4. **case 语句**(虽然不是循环,但可以用于基于条件的迭代):
```bash
case expression in
pattern1 )
# Commands to execute if expression matches pattern1
;;
pattern2 )
# Commands to execute if expression matches pattern2
;;
* )
# Default commands to execute
;;
esac
```
5. **if 语句**(虽然不是循环,但常用于条件判断):
```bash
if [ condition ]
then
# Commands to execute if condition is true
elif [ another condition ]
then
# Commands to execute if the first condition is false and another condition is true
else
# Commands to execute if all conditions are false
fi
```
6. **函数**(虽然不是循环命令,但可以包含循环):
```bash
function my_function {
# Commands to execute, can include loops
}
```