如何解决Shell循环变量覆盖问题并实现多变量对应格式输出?
Solution
The core issue with your original code is that single variables get overwritten in each loop iteration, losing all values except the last one. To fix this, we can combine all calculations into a single loop that processes each value pair and prints the result immediately:
words="0 3 4 5" idx=0 for i in $words; do height=$((20 + 10 * i)) x=$((10 + 15 * idx)) y=$(( (110 - height) / 2 )) printf "%-5d %-5d %d\n" "$height" "$x" "$y" ((idx++)) done
How this works:
- An index counter
idxtracks the position to calculatex(sincexfollows a sequence based on position, not the word value). - For each value in
$words, we compute the correspondingheight. yis calculated directly from the currentheightin the same iteration, avoiding lost values.printfensures consistent column spacing to match your desired output format.
Alternative approach using arrays:
If you prefer to store all values first before printing, use arrays to preserve each set of values:
words="0 3 4 5" words_array=($words) height_array=() x_array=() y_array=() # Populate height array for i in "${words_array[@]}"; do height_array+=($((20 + 10 * i))) done # Populate x array for j in {0..3}; do x_array+=($((10 + 15 * j))) done # Populate y array for h in "${height_array[@]}"; do y_array+=($(( (110 - h) / 2 ))) done # Print all values for idx in {0..3}; do printf "%-5d %-5d %d\n" "${height_array[$idx]}" "${x_array[$idx]}" "${y_array[$idx]}" done
Both approaches will produce your desired output:
20 10 45 50 25 30 60 40 25 70 55 20
内容的提问来源于stack exchange,提问作者GJO2
相关产品推荐
相关产品推荐

