bash shell 嵌套 for 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4847854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:08:52  来源:igfitidea点击:

bash shell nested for loop

bashshellnested-loops

提问by rashok

I want to write a nested for loop that has to work in the bash shell prompt. nested for loop in Single line command.

我想编写一个嵌套的 for 循环,它必须在 bash shell 提示符下工作。在单行命令中嵌套 for 循环。

For example,

例如,

for i in a b; do echo $i; done
a
b

In the above example, for loop is executed in a single line command right. Like this I have tried the nested for loop in the shell prompt. Its not working. How to do this. Please update me on this.

在上面的例子中,for 循环在单行命令中执行。像这样,我在 shell 提示中尝试了嵌套的 for 循环。它不工作。这该怎么做。请更新我。

回答by Daniel

This is not a nested loop, just a single loop. And the nested version works, too:

这不是嵌套循环,只是一个循环。嵌套版本也有效:

# for i in a b; do for j in a b; do echo $j; done; done
a
b
a
b

回答by Jonathan Leffler

One one line (semi-colons necessary):

一行一行(需要分号):

for i in 0 1 2 3 4 5 6 7 8 9; do for j in 0 1 2 3 4 5 6 7 8 9; do echo "$i$j"; done; done

Formatted for legibility (no semi-colons needed):

格式化为易读性(不需要分号):

for i in 0 1 2 3 4 5 6 7 8 9
do
    for j in 0 1 2 3 4 5 6 7 8 9
    do 
        echo "$i$j"
    done
done

There are different views on how the shell code should be laid out over multiple lines; that's about what I normally use, unless I put the next operation on the same line as the do(saving two lines here).

关于 shell 代码应该如何在多行上布局存在不同的看法;这就是我通常使用的内容,除非我将下一个操作与do(在此处保存两行)放在同一行上。

回答by user2867654

#!/bin/bash
# loop*figures.bash

for i in 1 2 3 4 5  # First loop.
do
    for j in $(seq 1 $i)
    do
        echo  -n "*" 
    done
    echo 
done
echo
# outputs
# *
# **
# ***
# ****
# *****

for i in 5 4 3 2 1 # First loop.
do
    for j in $(seq -$i -1)
    do
        echo  -n "*" 
    done
    echo 
done

# outputs
# *****
# ****
# ***
# **
# *

for i in 1 2 3 4 5  # First loop.
do
    for k in $(seq -5 -$i)
    do
        echo -n ' '
    done
    for j in $(seq 1 $i)
    do
        echo  -n "* " 
    done
    echo 
done
echo

# outputs
#     * 
#    * * 
#   * * * 
#  * * * * 
# * * * * * 

for i in 1 2 3 4 5  # First loop.
do
    for j in $(seq -5 -$i)
    do
        echo  -n "* " 
    done
    echo 
    for k in $(seq 1 $i)
    do
        echo -n ' '
    done
done
echo

# outputs
# * * * * * 
#  * * * * 
#   * * * 
#    * * 
#     *


exit 0