I have a Bash variable containing structured text spread across several lines, created with a heredoc. I want to append the variable to an environment file and later load it with `source`, but writing it with `echo INFO=$INFO` produces an invalid assignment because the value contains newlines and special characters. What is the safest way to serialize the variable so it can be restored elsewhere while preserving its exact contents?
4 Answers
If this is a Bash variable, use `declare -p` to generate a valid, safely quoted assignment instead of echoing the value. For example: `declare -p INFO > "$env_file"`, then later run `source "$env_file"`. Bash will recreate the variable with its newlines and special characters intact.
If the value is really JSON or another structured data format, consider storing it as data instead of as shell code. Write the JSON directly to a file and parse it with a suitable tool, or use Python if you need more involved structured-text handling. Shell sourcing is convenient, but only source files you trust because they can execute commands.
If you build the assignment manually, quote the entire value rather than using `echo INFO=$INFO`. A robust approach is to write a single-quoted shell value and escape any literal single quotes inside it. However, `declare -p INFO` is simpler and less error-prone for Bash variables.
Another Bash-specific option is parameter transformation: `printf 'INFO=%sn' "${INFO@Q}" >> "$env_file"`. The `@Q` form produces shell-escaped text that can be evaluated when the file is sourced. Make sure to quote the file path as well: `source "$env_file"`.

That worked for me—thanks!