跳转至

第 13 章 更多结构化命令

约 123 个字 30 行代码 1 张图片 预计阅读时间 1 分钟

for/while/until 循环与 C 风格 for。

13.1 for

Bash
for var in list; do
  commands
done

for file in /home/*; do echo $file; done

# C 风格
for (( i=1; i<=10; i++ )); do echo $i; done

13.2 while / until

Bash
while [ condition ]; do
  commands
done

until [ condition ]; do   # 条件为假时循环
  commands
done

读取文件

Bash
while IFS= read -r line; do
  echo "$line"
done < file

13.3 循环控制

Bash
break          # 跳出循环
break 2        # 跳出外层(嵌套层级)
continue       # 下一轮

13.4 并行处理

Bash
for f in *.log; do
  process $f &
done
wait           # 等待所有后台任务

13.5 timeout 与 xargs 并行

Bash
timeout 30s long_cmd           # 超时退出(124)
timeout -k 5 30s cmd           # 超时后 5 秒 SIGKILL

find . -name '*.test' -print0 | xargs -0 -P 4 -n 1 run_test
# -P 4 最多 4 进程并行

评论