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

如何解决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 idx tracks the position to calculate x (since x follows a sequence based on position, not the word value).
  • For each value in $words, we compute the corresponding height.
  • y is calculated directly from the current height in the same iteration, avoiding lost values.
  • printf ensures 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:45:32