如何在Bash中将本地变量加载到关联数组中?
Automatically Collect Local Variables into an Associative Array in Bash
If you want to automatically gather specific local variables (like var1, var2, var3) into an associative array without manually listing each one, you can leverage Bash's local -p command to list local variables in the current scope, then parse those lines to extract names and values.
Here's a practical implementation tailored to your use case:
#!/bin/bash function build_vars_array() { # Define your local variables first (these are the ones you want to collect) local var1="db_username=admin" local var2="nginx_root=/var/www/app" local var3="sql_port=5432" local temp_var="skip_this" # Example variable to exclude from the array # Initialize the target associative array declare -A vars_list # Loop through all local variable declarations in the current scope while IFS= read -r line; do # Skip variables that don't match your naming pattern (varN) if [[ ! "$line" =~ ^local\ var[0-9]+= ]]; then continue fi # Extract the variable name (e.g., var1 from "local var1='value'") local var_name=$(echo "$line" | sed -E 's/^local ([^=]+)=.*/\1/') # Safely retrieve the variable's value using indirect expansion local var_value="${!var_name}" # Add the key-value pair to the associative array vars_list["$var_name"]="$var_value" done < <(local -p) # Feed local variable list into the loop (avoids subshell issues) # Optional: Verify the array contents echo "Collected variables for templating:" for key in "${!vars_list[@]}"; do echo "$key: ${vars_list[$key]}" done } # Execute the function build_vars_array
How This Works:
local -p: This command outputs all local variables in the current function scope in the formatlocal var_name='value', which we can parse.- Pattern Matching: The regex
^local\ var[0-9]+=filters only variables namedvar1,var2, etc., skipping any other local variables you don't want to include. - Indirect Expansion:
${!var_name}safely retrieves the value of the variable whose name is stored invar_name—this is a secure alternative to usingevalfor variable interpolation. - Associative Array: We populate
vars_listwith each matching variable's name as the key and its value as the value, ready for use in templating SQL/Nginx files.
Customization Tips:
- If you want to include all local variables except the array itself, adjust the skip condition to:
if [[ "$line" =~ ^local\ vars_list= ]]; then continue fi - Modify the regex pattern to match your actual variable naming convention (e.g.,
^local\ app_for variables starting withapp_).
This approach keeps your script maintainable—you won't have to update the array manually every time you add a new variable.
内容的提问来源于stack exchange,提问作者Alexi Theodore
相关产品推荐
相关产品推荐

