Bash脚本技术问询:如何在for循环内为blocks数组追加curr_block元素?
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[@]}withfor line in "${fail_no[@]}"to properly loop through every element in thefail_noarray (no accidental word-splitting!). - Replace
sed "$line!d" $1withsed "$line!d" "$1"to handle filenames with spaces correctly. - Wrap variables like
$new_linein 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_blockvalues were actually being stored all along! - If you're still missing values, double-check that the
fail_noarray contains every line number you intend to process.
内容的提问来源于stack exchange,提问作者Birbal

