Safest way to store environment variable value in a fileWhy is printf better than echo?Bash shell functions...

Does fossil fuels use since 1990 account for half of all the fossil fuels used in history?

80's/90's superhero cartoon with a man on fire and a man who made ice runways like Frozone

Understanding the point of a kölsche Witz

On the Rømer experiments and the speed of light

Is it feasible to get a hash collision for CRC32, MD-5 and SHA-1 on one file?

How can I decide if my homebrew item should require attunement?

Why is the result of ('b'+'a'+ + 'a' + 'a').toLowerCase() 'banana'?

When were the tantalum capacitors first used in computing?

A torrent of foreign terms

Why are Tucker and Malcolm not dead?

How does "Te vas a cansar" mean "You're going to get tired"?

How does proof assistant organize knowledge?

Loading military units into ships optimally, using backtracking

PhD advisor lost funding, need advice

Are differences between uniformly distributed numbers uniformly distributed?

What is this "Table of astronomy" about?

How do some PhD students get 10+ papers? Is that what I need for landing good faculty position?

What should I call bands of armed men in the Middle Ages?

If clocks themselves are based on light signals, wouldn't we expect the measured speed of light to always be the same constant?

Heating Margarine in Pan = loss of calories?

Safest way to store environment variable value in a file

Is this curved text blend possible in Illustrator?

How can I categorize files in a directory based on their content?

Is there any way to stop a user from creating executables and running them?



Safest way to store environment variable value in a file


Why is printf better than echo?Bash shell functions and understanding shell shockLooping through lines in file using bash and passing to variable. Resulting variable is not the same value as file, why?Substitute variable in value of chpst loaded environment variablebash script that incorporates content from a file as part of a commandNeed to capture stdout and modify variable by reference from function in bashSED or AWK?: Add character to each line after found patternWhy can't I print a variable I can see in the output of env?sed - calling a variable from a file with multilineBASH: declare a local function in remote host with interactive shellSet shell variable then invoke subprocess fails






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







3















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.)










share|improve this question

























  • What will use the file? Will it be used to set the value again in a shell script, or by some other tool?

    – muru
    8 hours ago






  • 1





    @drewbenn echo -- "$KEY" would not help. It would output -- -n.

    – Kusalananda
    8 hours ago








  • 1





    @Kusalananda, I'm a bit disappointed that all my shells consistently output -- -n

    – ilkkachu
    8 hours ago













  • This is one of the reasons why printf is always better than echo when you don't have complete control over what input you want to print.

    – terdon
    8 hours ago











  • @ilkkachu Hmm... Usually, consistency is considered a good thing ;-)

    – Kusalananda
    7 hours ago




















3















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.)










share|improve this question

























  • What will use the file? Will it be used to set the value again in a shell script, or by some other tool?

    – muru
    8 hours ago






  • 1





    @drewbenn echo -- "$KEY" would not help. It would output -- -n.

    – Kusalananda
    8 hours ago








  • 1





    @Kusalananda, I'm a bit disappointed that all my shells consistently output -- -n

    – ilkkachu
    8 hours ago













  • This is one of the reasons why printf is always better than echo when you don't have complete control over what input you want to print.

    – terdon
    8 hours ago











  • @ilkkachu Hmm... Usually, consistency is considered a good thing ;-)

    – Kusalananda
    7 hours ago
















3












3








3








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.)










share|improve this question














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.)







bash scripting






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 9 hours ago









Old ProOld Pro

6122 gold badges6 silver badges15 bronze badges




6122 gold badges6 silver badges15 bronze badges
















  • What will use the file? Will it be used to set the value again in a shell script, or by some other tool?

    – muru
    8 hours ago






  • 1





    @drewbenn echo -- "$KEY" would not help. It would output -- -n.

    – Kusalananda
    8 hours ago








  • 1





    @Kusalananda, I'm a bit disappointed that all my shells consistently output -- -n

    – ilkkachu
    8 hours ago













  • This is one of the reasons why printf is always better than echo when you don't have complete control over what input you want to print.

    – terdon
    8 hours ago











  • @ilkkachu Hmm... Usually, consistency is considered a good thing ;-)

    – Kusalananda
    7 hours ago





















  • What will use the file? Will it be used to set the value again in a shell script, or by some other tool?

    – muru
    8 hours ago






  • 1





    @drewbenn echo -- "$KEY" would not help. It would output -- -n.

    – Kusalananda
    8 hours ago








  • 1





    @Kusalananda, I'm a bit disappointed that all my shells consistently output -- -n

    – ilkkachu
    8 hours ago













  • This is one of the reasons why printf is always better than echo when you don't have complete control over what input you want to print.

    – terdon
    8 hours ago











  • @ilkkachu Hmm... Usually, consistency is considered a good thing ;-)

    – Kusalananda
    7 hours ago



















What will use the file? Will it be used to set the value again in a shell script, or by some other tool?

– muru
8 hours ago





What will use the file? Will it be used to set the value again in a shell script, or by some other tool?

– muru
8 hours ago




1




1





@drewbenn echo -- "$KEY" would not help. It would output -- -n.

– Kusalananda
8 hours ago







@drewbenn echo -- "$KEY" would not help. It would output -- -n.

– Kusalananda
8 hours ago






1




1





@Kusalananda, I'm a bit disappointed that all my shells consistently output -- -n

– ilkkachu
8 hours ago







@Kusalananda, I'm a bit disappointed that all my shells consistently output -- -n

– ilkkachu
8 hours ago















This is one of the reasons why printf is always better than echo when you don't have complete control over what input you want to print.

– terdon
8 hours ago





This is one of the reasons why printf is always better than echo when you don't have complete control over what input you want to print.

– terdon
8 hours ago













@ilkkachu Hmm... Usually, consistency is considered a good thing ;-)

– Kusalananda
7 hours ago







@ilkkachu Hmm... Usually, consistency is considered a good thing ;-)

– Kusalananda
7 hours ago












2 Answers
2






active

oldest

votes


















3














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 '%sn' "$KEY" as you would do when you output any variable data.



So,



printf '%sn' "$KEY" >key.pem


or



printf 'BEGIN %s ENDn' "$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:




  • Why is printf better than echo?






share|improve this answer



































    1














    Many systems have a printenv command that outputs the contents of the given environment variable followed by one newline character to standard output:



    printenv 'My Env Var' > file


    Would store the content of the My Env Var variable followed by NL into file in all shells on those systems.



    For environment variables that are mapped to shell variables (includes at least those whose name starts with an ASCII letter or underscore and are followed by 0 or more ASCII letters, digits or underscore, and are not otherwise special variables set by the shell), in Bourne-like shells (also works in fish), you can do the same with:



    printf '%sn' "$ENVVAR" > file


    (though if the variable is unset, that will still store an empty line into file)



    In rc-like shells:



    echo $ENVVAR > file


    (same caveat as above)



    In csh-like shells:



    printf '%sn' $ENVVAR:q > file


    (if the variable is not set, it will fail and not overwrite file)



    Some implementations/versions of ksh don't have printf builtin. In those, you could also do:



    print -r -- "$ENVVAR" > file





    share|improve this answer




























      Your Answer








      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "106"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f535214%2fsafest-way-to-store-environment-variable-value-in-a-file%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      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 '%sn' "$KEY" as you would do when you output any variable data.



      So,



      printf '%sn' "$KEY" >key.pem


      or



      printf 'BEGIN %s ENDn' "$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:




      • Why is printf better than echo?






      share|improve this answer
































        3














        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 '%sn' "$KEY" as you would do when you output any variable data.



        So,



        printf '%sn' "$KEY" >key.pem


        or



        printf 'BEGIN %s ENDn' "$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:




        • Why is printf better than echo?






        share|improve this answer






























          3












          3








          3







          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 '%sn' "$KEY" as you would do when you output any variable data.



          So,



          printf '%sn' "$KEY" >key.pem


          or



          printf 'BEGIN %s ENDn' "$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:




          • Why is printf better than echo?






          share|improve this 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 '%sn' "$KEY" as you would do when you output any variable data.



          So,



          printf '%sn' "$KEY" >key.pem


          or



          printf 'BEGIN %s ENDn' "$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:




          • Why is printf better than echo?







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 6 hours ago

























          answered 9 hours ago









          KusalanandaKusalananda

          159k18 gold badges315 silver badges501 bronze badges




          159k18 gold badges315 silver badges501 bronze badges




























              1














              Many systems have a printenv command that outputs the contents of the given environment variable followed by one newline character to standard output:



              printenv 'My Env Var' > file


              Would store the content of the My Env Var variable followed by NL into file in all shells on those systems.



              For environment variables that are mapped to shell variables (includes at least those whose name starts with an ASCII letter or underscore and are followed by 0 or more ASCII letters, digits or underscore, and are not otherwise special variables set by the shell), in Bourne-like shells (also works in fish), you can do the same with:



              printf '%sn' "$ENVVAR" > file


              (though if the variable is unset, that will still store an empty line into file)



              In rc-like shells:



              echo $ENVVAR > file


              (same caveat as above)



              In csh-like shells:



              printf '%sn' $ENVVAR:q > file


              (if the variable is not set, it will fail and not overwrite file)



              Some implementations/versions of ksh don't have printf builtin. In those, you could also do:



              print -r -- "$ENVVAR" > file





              share|improve this answer






























                1














                Many systems have a printenv command that outputs the contents of the given environment variable followed by one newline character to standard output:



                printenv 'My Env Var' > file


                Would store the content of the My Env Var variable followed by NL into file in all shells on those systems.



                For environment variables that are mapped to shell variables (includes at least those whose name starts with an ASCII letter or underscore and are followed by 0 or more ASCII letters, digits or underscore, and are not otherwise special variables set by the shell), in Bourne-like shells (also works in fish), you can do the same with:



                printf '%sn' "$ENVVAR" > file


                (though if the variable is unset, that will still store an empty line into file)



                In rc-like shells:



                echo $ENVVAR > file


                (same caveat as above)



                In csh-like shells:



                printf '%sn' $ENVVAR:q > file


                (if the variable is not set, it will fail and not overwrite file)



                Some implementations/versions of ksh don't have printf builtin. In those, you could also do:



                print -r -- "$ENVVAR" > file





                share|improve this answer




























                  1












                  1








                  1







                  Many systems have a printenv command that outputs the contents of the given environment variable followed by one newline character to standard output:



                  printenv 'My Env Var' > file


                  Would store the content of the My Env Var variable followed by NL into file in all shells on those systems.



                  For environment variables that are mapped to shell variables (includes at least those whose name starts with an ASCII letter or underscore and are followed by 0 or more ASCII letters, digits or underscore, and are not otherwise special variables set by the shell), in Bourne-like shells (also works in fish), you can do the same with:



                  printf '%sn' "$ENVVAR" > file


                  (though if the variable is unset, that will still store an empty line into file)



                  In rc-like shells:



                  echo $ENVVAR > file


                  (same caveat as above)



                  In csh-like shells:



                  printf '%sn' $ENVVAR:q > file


                  (if the variable is not set, it will fail and not overwrite file)



                  Some implementations/versions of ksh don't have printf builtin. In those, you could also do:



                  print -r -- "$ENVVAR" > file





                  share|improve this answer













                  Many systems have a printenv command that outputs the contents of the given environment variable followed by one newline character to standard output:



                  printenv 'My Env Var' > file


                  Would store the content of the My Env Var variable followed by NL into file in all shells on those systems.



                  For environment variables that are mapped to shell variables (includes at least those whose name starts with an ASCII letter or underscore and are followed by 0 or more ASCII letters, digits or underscore, and are not otherwise special variables set by the shell), in Bourne-like shells (also works in fish), you can do the same with:



                  printf '%sn' "$ENVVAR" > file


                  (though if the variable is unset, that will still store an empty line into file)



                  In rc-like shells:



                  echo $ENVVAR > file


                  (same caveat as above)



                  In csh-like shells:



                  printf '%sn' $ENVVAR:q > file


                  (if the variable is not set, it will fail and not overwrite file)



                  Some implementations/versions of ksh don't have printf builtin. In those, you could also do:



                  print -r -- "$ENVVAR" > file






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 6 hours ago









                  Stéphane ChazelasStéphane Chazelas

                  329k57 gold badges640 silver badges1008 bronze badges




                  329k57 gold badges640 silver badges1008 bronze badges

































                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Unix & Linux Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f535214%2fsafest-way-to-store-environment-variable-value-in-a-file%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

                      Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

                      Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...