簡體   English   中英

使用多個數組的bash腳本

[英]bash script using multiple arrays

我想在包含兩個數組的 for 循環中運行多個命令。 換句話說,我需要有一個嵌套的 for 循環,它將通過以下過程執行命令:

  1. 回聲一

  2. 回聲 8df6

  3. 回聲二

  4. 回聲 b4c2

  5. 回聲三

  6. 回聲 9 時尚

    下面是一些嘗試過但無法應用所需的代碼。

#!/bin/bash
numbers=(one two three)

numbersid=(8df6 b4c2 9fad)

for m in "${numbers[@]}"
do
    echo "${m}";
for n in "${numbersid[@]}"
do
    echo "${n}" ;
done
done;

謝謝你。

在這種情況下,一個循環就足夠了:

#!/bin/bash
numbers=(one two three)
numbersid=(8df6 b4c2 9fad)

for index in 0 1 2
do      
        echo ${numbers[$index]}
        echo ${numbersid[$index]}
done

給出:

one
8df6
two
b4c2
three
9fad

請注意,bash 可以幫助您提取數組的索引:

#...............v
for index in "${!numbers[@]}"; do
        echo ${numbers[index]}
        echo ${numbersid[index]}
done

如果你檢查你的代碼的輸出,你會發現,有2 for在彼此內的循環導致在運行嵌套for循環第一的每次迭代for循環。

因此,在每個number您都會打印出所有的numberids

您的目標是numberid打印numbernumberid 所以你想遍歷number數組的長度。 然后打印number及其id

您可以通過以下方式實現。

#!/bin/bash
numbers=(one two three)

numbersid=(8df6 b4c2 9fad)

for i in "${!numbers[@]}"
do
    echo "${numbers[i]}";
    echo "${numbersid[i]}";
done;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM