如何在Bash dialog中实现可变数量的输入字段?
Your issue comes from using a string variable to store command arguments—Bash doesn’t parse embedded quotes correctly, leading to messed-up argument splitting. The proper way to handle variable-length arguments in Bash is using arrays, which preserve individual arguments exactly as intended.
Solution: Use an Array for Form Fields
Arrays let you build each input field’s components as separate elements, which Bash will pass to dialog correctly. Here’s how to adjust your code:
# Set the number of input fields you need ITEMS=4 # Initialize empty array to hold form field arguments form_fields=() # Populate the array with dynamic fields for ((i=1; i<=$ITEMS; i++)); do # Use indirect expansion to get the value of $Item1, $Item2, etc. item_value="${!Item$i}" # Add each component of the field to the array form_fields+=( "Item $i :" # Label text "$i" "1" # Row and column position for the label "$item_value" # Default value for the input field "$i" "15" # Row and column position for the input box "65" "256" # Width of the input box and maximum input length ) done # Run the dialog command with the array of fields exec 3>&1 VALUES=$(dialog --ok-label "Submit" \ --backtitle "Test input form" \ --title " Type information in " \ --form "" 12 95 0 \ "${form_fields[@]}" \ 2>&1 1>&3) exec 3>&-
Key Notes:
- Indirect Expansion:
${!Item$i}retrieves the value of variables likeItem1orItem2dynamically, replacing the escaped\$Item$iin your original code and ensuring correct variable interpolation. - Array Expansion:
"${form_fields[@]}"expands the array into separate arguments, preserving spaces and avoiding the quoting issues you faced with a string variable. Each array element is treated as a single argument todialog.
Why Your Original Approach Failed
When you build a string variable with embedded quotes, Bash treats those quotes as literal characters, not as syntax to group arguments. For example, your ITEMSTRING would contain the literal "Item 1 :" (with quotes), which dialog interprets as part of the label text instead of recognizing it as a single argument. This causes mismatched argument counts and the errors you saw.
Alternative (Not Recommended): Using eval
While you could use eval to force parsing of the string as command arguments, this is unsafe if any input contains special characters (like spaces, quotes, or shell metacharacters). Arrays are far more reliable and secure for this use case.
内容的提问来源于stack exchange,提问作者Howard Rogers

