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

Bash脚本技术问询:如何在for循环内为blocks数组追加curr_block元素?

Troubleshooting Your Bash Array Assignment Issue

Hey there! Let's dig into why your blocks array isn't capturing all the curr_block values you expect. I spot a couple of potential issues in your script that might be causing this:

1. Misleading Array Output (Common Bash Gotcha!)

First off, when you run echo $blocks at the end, this only prints the first element of the array. To see all values stored in blocks, you need to use:

echo "${blocks[@]}"

This is a super easy mistake to make—don't let the incomplete output trick you into thinking values aren't being added!

2. Unquoted Variables Breaking Iteration & Command Execution

Several unquoted variables in your script can cause unexpected behavior, especially if your filenames, line numbers, or array elements have spaces or special characters:

  • Replace for line in ${fail_no[@]} with for line in "${fail_no[@]}" to properly loop through every element in the fail_no array (no accidental word-splitting!).
  • Replace sed "$line!d" $1 with sed "$line!d" "$1" to handle filenames with spaces correctly.
  • Wrap variables like $new_line in quotes wherever you use them to avoid unintended splitting of your text.

3. Corrected Script Example

Here's your script with these fixes applied, plus a modern Bash tweak (using $() instead of backticks for command substitution—it's more readable and avoids escaping headaches):

blocks=()
for line in "${fail_no[@]}"
do
    new_line=$(sed "$line!d" "$1")
    command=$(echo "$new_line" | cut -d ',' -f2)
    while [[ "$new_line" != *"$PROJ_NAME"* ]]
    do
        line=$((line-1))
        new_line=$(sed "$line!d" "$1")
    done
    curr_block=$(echo "$new_line" | cut -d ',' -f1)
    echo "$curr_block"
    blocks+=("$curr_block")
done
# Print all elements in the array correctly
echo "${blocks[@]}"

Quick Next Steps

  • Try running the script with the corrected array output line first—you might find all your curr_block values were actually being stored all along!
  • If you're still missing values, double-check that the fail_no array contains every line number you intend to process.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:49:01