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.)
echo -- "$KEY"
would not help. It would output-- -n
. – Kusalananda Aug 12 '19 at 17:45-- -n
– ilkkachu Aug 12 '19 at 17:53printf
is always better thanecho
when you don't have complete control over what input you want to print. – terdon Aug 12 '19 at 18:12rc
clone for Unix and its es/akanga derivatives supportecho --
. Early versions ofzsh
did as well, but the end-of-option delimiter later changed to-
for consistency with Bourne/Korn shell and builtins I suppose. – Stéphane Chazelas Aug 13 '19 at 07:22fish
(2.7.1) too. I'm not sure if I should say I'm happy now... – ilkkachu Aug 13 '19 at 07:32echo
from supporting an end-of-option marker. I did ask that zsh's-
be allowed but it was rejected. See http://austingroupbugs.net/view.php?id=1222 (linked from the Why is printf better than echo? Q&A) – Stéphane Chazelas Aug 13 '19 at 07:37