使用Windows命令行将多行环境变量回显到文本文件 [英] Echo a multi line environment variable to a text file using Windows Command Line
问题描述
我有一个环境变量%SSH_PRIVATE_KEY%
,并希望使用命令行将其打印到文件中,而不使用批处理文件.这是因为我需要在Gitlab-Ci .yml脚本中使用此文件.
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. This is because I need to use this file in a Gitlab-Ci .yml script.
在Linux中,这很简单:
echo "$SSH_PRIVATE_KEY" > ~/.ssh/id_rsa
这会生成:
-----BEGIN RSA PRIVATE KEY-----
DHHDpgIFFFFAQEA4s5JARKOiF/dfherreh/qeGLNaryra7rt927okJmonpJHyCbA5SRyjsST/oC
tJx+YJ0BaNbbHtpbjbMeWgqKPXNAIRng30TXCOLLKverteygerg/ererg/GVFfd5T1v/qY2rGCN
v9yHSw89upy8pA+HvAFFFFHDb2YUAgpyYMqCcZ3vGY0/NDBxQQwDKwrefqwef/wefweqe/wwALb
以此类推.
但是,如果我尝试在Windows中:
echo "%SSH_PRIVATE_KEY%" > C:\runner\builds\66092d15\0\myproject\.ssh\id_rsa
它生成以下输出:
"-----BEGIN RSA PRIVATE KEY-----
因为一旦到达%SSH_PRIVATE_KEY%
中的换行符,它就会逃避echo命令.
Because as soon as it reaches the newline character in %SSH_PRIVATE_KEY%
it escapes the echo command.
如何使用Windows命令行将完整的%SSH_PRIVATE_KEY%
打印到文件?
How can I print the full %SSH_PRIVATE_KEY%
to a file using the windows command line?
推荐答案
事实上,Blue7是正确的,但是当他/她被否决时,对于那些没有读过gitlab-ci的人来说,答案很长:
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:
用于!要工作,必须启用DelayedExpansion,并且它似乎仅在批处理文件中起作用.在gitlab中,默认情况下就是这种情况.默认情况下,cmd将首先扩展环境变量,然后对其进行解释.因此,当您编写 echo%SSH_PRIVATE_KEY%"
cmd实际上会看到
For ! to work DelayedExpansion must be enabled, and it seems to only work in batch-files. In gitlab this is the case by default. By default cmd will first expand the environment variable and then interpret it. Thus when you write echo "%SSH_PRIVATE_KEY%"
cmd actually sees
echo "-----BEGIN RSA PRIVATE KEY-----
DHHDpgIFFFFAQEA4s5JARKOiF/dfherreh/qeGLNaryra7rt927okJmonpJHyCbA5SRyjsST/oC
...
是的,包括"
!为避免这种情况,您需要启用后期扩展 setlocal EnableDelayedExpansion
.在延迟扩展的情况下,环境变量会先扩展,然后再传递给环境变量.因此,也无需使用"
.搜索 EnableDelayedExpansion
将为您提供许多其他信息.
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 "
. Searching for EnableDelayedExpansion
will provide you with lots of additional information.
这篇关于使用Windows命令行将多行环境变量回显到文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!