You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash中能否在for-in循环中使用多个变量?

How to Loop Through Multiple Variable Lists in Bash (Pairing Corresponding Elements)

Got it, the syntax you tried (for i in 1 2 3 4, j in 7 8 9 0 do echo $i"="$j done) doesn't work in bash (or most common Unix shells) because the standard for loop doesn't support declaring multiple variable lists like that directly. But there are several simple, reliable ways to get the paired output you want (1=7, 2=8, etc.). Let's break them down:

Method 1: Use Arrays + Index-Based Loop

This is the most readable and maintainable approach for most cases. Define two arrays holding your values, then loop through their indices to pair elements:

# Define your value lists as arrays
first_set=(1 2 3 4)
second_set=(7 8 9 0)

# Loop through each index of the first array
for index in "${!first_set[@]}"; do
    echo "${first_set[$index]}=${second_set[$index]}"
done

How it works:

  • ${!first_set[@]} returns all the indices of the first_set array (in this case, 0 1 2 3).
  • We use each index to pull the corresponding element from both arrays, ensuring they're paired correctly.

Method 2: Use paste + while read

If you prefer not to use arrays, you can use the paste command to merge your two value lists line-by-line, then read each paired line with a while loop:

# Merge the two value lists (each value on its own line) and read pairs
paste <(printf "%s\n" 1 2 3 4) <(printf "%s\n" 7 8 9 0) | while read i j; do
    echo "$i=$j"
done

How it works:

  • printf "%s\n" 1 2 3 4 prints each value on a new line. The <(...) syntax turns this output into a temporary file-like input for paste.
  • paste combines the two input streams, joining corresponding lines with a tab.
  • while read i j splits each combined line into two variables (i and j) and runs the echo command for each pair.

Method 3: C-Style for Loop (Bash-Specific)

If you know the exact number of elements, you can use a C-style loop to iterate through indices:

first_set=(1 2 3 4)
second_set=(7 8 9 0)

# Loop from index 0 to the length of the array minus 1
for ((i=0; i < ${#first_set[@]}; i++)); do
    echo "${first_set[$i]}=${second_set[$i]}"
done

Important Note:

Make sure both of your value lists have the same number of elements. If one is longer than the other, the shorter list will have empty values for the extra indices, which might lead to unexpected output (like 4= if the second list was shorter).

内容的提问来源于stack exchange,提问作者CuriousNewbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 08:53:15