如何读取.tfvars每行内容并在Bash中导出为环境变量?
Let's break down what's going wrong here and fix it. Your current script is failing because it doesn't properly handle the whitespace around the = in your .tfvars entries, and it doesn't correctly parse key-value pairs into a format Bash accepts for environment variables (which requires KEY=VALUE with no spaces in the variable name).
Why the Error Happens
When you run tr -d "\"" on a line like region = "us-east-2", you end up with region = us-east-2. Bash can't export this because the variable name would include spaces (and the = is treated as part of the name), leading to the invalid identifier error.
Working Solution
Here's a robust script that properly parses simple string variables from your .tfvars file and exports them as Bash environment variables:
# Path to your .tfvars file variables_file_2="your-file.tfvars" while IFS= read -r line; do # Skip empty lines and comment lines (lines starting with #, possibly with leading spaces) [[ "$line" =~ ^[[:space:]]*# || -z "$line" ]] && continue # Extract the variable key (left of =, trimmed of whitespace) key=$(echo "$line" | awk -F '=' '{gsub(/^[ \t]+|[ \t]+$/, "", $1); print $1}') # Extract the value (right of =, trimmed of whitespace and surrounding quotes) value=$(echo "$line" | awk -F '=' '{ $1 = ""; gsub(/^[ \t]*=[ \t]*|"|\047/, "", $0); gsub(/^[ \t]+|[ \t]+$/, "", $0); print $0 }') # Export the key-value pair as an environment variable export "$key=$value" done < "$variables_file_2"
How This Works
- Skip Comments/Empty Lines: The script first ignores any line that's empty or starts with a comment (even with leading spaces).
- Clean Up the Key: It extracts the variable name from the left side of the
=, stripping any leading/trailing whitespace. - Clean Up the Value: It grabs everything to the right of the
=, removes surrounding quotes (both single and double), trims extra whitespace, and removes the=itself. - Valid Export Format: By formatting the output as
KEY=VALUE, Bash can correctly interpret and export the environment variable.
Alternative One-Liner with Awk
If you prefer a more concise approach, you can use awk to generate and run the export commands directly:
awk '!/^[[:space:]]*(#|$)/ { gsub(/^[[:space:]]+|[[:space:]]+$/, "", $1); key = $1; $1 = ""; gsub(/^[[:space:]]*=[[:space:]]*|"|\047/, "", $0); printf("export %s=%s\n", key, $0); }' "$variables_file_2" | bash
Important Notes
- This solution works for simple string variables in .tfvars. If your file has complex types like lists (
regions = ["us-east-1", "us-west-2"]) or maps (tags = { Name = "my-instance" }), Bash can't natively handle these as environment variables—you'd need additional parsing logic to convert them into a Bash-compatible format (like JSON strings, for example). - If your variable values contain special characters (like
$,!, or spaces), you'll need to quote the value when exporting. Modify the export line to:export "$key=\"$value\""
内容的提问来源于stack exchange,提问作者deagleshot

