> For the complete documentation index, see [llms.txt](https://linuxstory.gitbook.io/advanced-bash-scripting-guide-in-chinese/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://linuxstory.gitbook.io/advanced-bash-scripting-guide-in-chinese/zheng-wen/part3/11_loops_and_branches/11_2_nested_loops.md).

# 11.2 嵌套循环

嵌套循环，顾名思义就是在循环里面还有循环。外层循环会不断的触发内层循环直到外层循环结束。当然，你仍然可以使用 `break` 可以终止外层或内层的循环。

样例 11-20. 嵌套循环

```bash
#!/bin/bash
# nested-loop.sh: 嵌套 "for" 循环。

outer=1             # 设置外层循环计数器。

# 外层循环。
for a in 1 2 3 4 5 
do
  echo "Pass $outer in outer loop."
  echo "---------------------"
  inner=1           # 重设内层循环计数器。
  
  # =====================================
  # 内层循环。
  for b in 1 2 3 4 5
  do
    echo "Pass $inner in inner loop."
    let "inner+=1"  # 增加内层循环计数器。
  done
  # 内层循环结束。
  # =====================================
  
  let "outer+=1"    # 增加外层循环计数器。
  echo              # 在每次外层循环输出中加入空行。
done
# 外层循环结束。

exit 0
```

查看 [样例 27-11](http://tldp.org/LDP/abs/html/arrays.html#BUBBLE) 详细了解嵌套 [while 循环](http://tldp.org/LDP/abs/html/loops1.html#WHILELOOPREF)。查看 [样例 27-13](http://tldp.org/LDP/abs/html/arrays.html#EX68) 详细了解嵌套 [until 循环](http://tldp.org/LDP/abs/html/loops1.html#UNTILLOOPREF)。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://linuxstory.gitbook.io/advanced-bash-scripting-guide-in-chinese/zheng-wen/part3/11_loops_and_branches/11_2_nested_loops.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
