Bash中能否在for-in循环中使用多个变量?
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 thefirst_setarray (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 4prints each value on a new line. The<(...)syntax turns this output into a temporary file-like input forpaste.pastecombines the two input streams, joining corresponding lines with a tab.while read i jsplits each combined line into two variables (iandj) and runs theechocommand 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

