Bash – Safest Way to Store Environment Variable in a File

bashscripting

I am using bash and most interested in an answer for bash, but you can answer about how to do it in other shells if you want.

I have an environment variable, KEY, and I want to store the value of that environment variable in a a file. Currently I am doing

echo "${KEY}" > ./key.pem

In practice this seems to be OK, but in theory this breaks when KEY=-n.

$ export KEY=-n
$ echo BEGIN "${KEY}" END
BEGIN -n END
$ echo "${KEY}" END
END$

So, is there a better way to store the value of a single environment variable in a file? (Note that export and declare will include the name of the variable in their outputs, which is no good for me.)

Best Answer

If it's storing for the sake of reading it in later (in a bash script), just use declare -p KEY and then source the file to read it in again. If you just want to store the value, use printf '%s\n' "$KEY" as you would do when you output any variable data.

So,

printf '%s\n' "$KEY" >key.pem

or

printf 'BEGIN %s END\n' "$KEY" >key.pem

or whatever you need to output.

Your issue occurs since -n is a valid option to echo in bash. The strings -e and -E (and combinations like -neEne) would also cause issues in bash, for the same reason. Depending on how bash is built or the environment or options, backslash characters in arguments may also be a problem.

These issues and more are outlined in the following Q/A:

Related Question