简体   繁体   English

使用Windows命令行将多行环境变量回显到文本文件

[英]Echo a multi line environment variable to a text file using Windows Command Line

I have an environment variable %SSH_PRIVATE_KEY% and would like to print this to a file using the command line, without using a batch file. 我有一个环境变量%SSH_PRIVATE_KEY% ,想使用命令行将其打印到文件中,而不使用批处理文件。 This is because I need to use this file in a Gitlab-Ci .yml script. 这是因为我需要在Gitlab-Ci .yml脚本中使用此文件。

In Linux, this is as simple as: 在Linux中,这很简单:

echo "$SSH_PRIVATE_KEY" > ~/.ssh/id_rsa 

And this generates: 这会生成:

-----BEGIN RSA PRIVATE KEY-----
DHHDpgIFFFFAQEA4s5JARKOiF/dfherreh/qeGLNaryra7rt927okJmonpJHyCbA5SRyjsST/oC
tJx+YJ0BaNbbHtpbjbMeWgqKPXNAIRng30TXCOLLKverteygerg/ererg/GVFfd5T1v/qY2rGCN
v9yHSw89upy8pA+HvAFFFFHDb2YUAgpyYMqCcZ3vGY0/NDBxQQwDKwrefqwef/wefweqe/wwALb 

And so on. 等等。

However in Windows, if I try: 但是在Windows中,如果我尝试:

echo "%SSH_PRIVATE_KEY%" >  C:\runner\builds\66092d15\0\myproject\.ssh\id_rsa

It generates this output: 它生成以下输出:

"-----BEGIN RSA PRIVATE KEY-----

Because as soon as it reaches the newline character in %SSH_PRIVATE_KEY% it escapes the echo command. 因为一旦到达%SSH_PRIVATE_KEY%的换行符,它就会转义echo命令。

How can I print the full %SSH_PRIVATE_KEY% to a file using the windows command line? 如何使用Windows命令行将完整的%SSH_PRIVATE_KEY%打印到文件?

要获取所有行,请使用echo !VARIABLENAME!

echo !SSH_PRIVATE_KEY! >  C:\runner\builds\66092d15\0\myproject\.ssh\id_rsa

Actually Blue7 is right, but as he/she was down voted, here comes the long answer for anyone who did not read that this is gitlab-ci realted: 实际上,Blue7是正确的,但是由于他/她被否决了,所以对于那些没有读过gitlab-ci的人来说,答案很长:

For ! 为! to work DelayedExpansion must be enabled, and it seems to only work in batch-files. 要工作,必须启用DelayedExpansion,并且它似乎仅在批处理文件中工作。 In gitlab this is the case by default. 在gitlab中,默认情况下就是这种情况。 By default cmd will first expand the environment variable and then interpret it. 默认情况下,cmd将首先扩展环境变量,然后对其进行解释。 Thus when you write echo "%SSH_PRIVATE_KEY%" cmd actually sees 因此,当您编写echo "%SSH_PRIVATE_KEY%" cmd实际上会看到

echo "-----BEGIN RSA PRIVATE KEY-----
DHHDpgIFFFFAQEA4s5JARKOiF/dfherreh/qeGLNaryra7rt927okJmonpJHyCbA5SRyjsST/oC
...

Yes, including the " ! To avoid this, you need to enable late expansion setlocal EnableDelayedExpansion . With delayed expansion the environment variables are extended right before passing them to the application. Thus there is also no need for using " . 是的,包括" !为避免这种情况,您需要启用后期扩展setlocal EnableDelayedExpansion 。通过延迟扩展,环境变量会在将其传递给应用程序之前进行扩展。因此,也无需使用" Searching for EnableDelayedExpansion will provide you with lots of additional information. 搜索EnableDelayedExpansion将为您提供许多其他信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM