打印环境变量名称到文件,而不是从Linux命令行中打印其值。

huangapple go评论65阅读模式
英文:

How to print ENV VAR name to file, NOT VALUE from linux cli

问题

我有这个:

cat > ~/add_api_txt_hook.sh <<EOF
#!/bin/bash
...
echo $MY_ENV_VAR
EOF


当创建此文件时,MY_ENV_VAR未设置。因此它在文件中变成了“”。
我希望文件内容是:

#!/bin/bash
...
echo $MY_ENV_VAR


而不是:

#!/bin/bash
...
echo ""


如何将实际的ENV VAR ***KEY*** 打印到文件中?我在互联网上搜索过,但它只返回如何将值打印到文件中的方法。
尝试了谷歌和各种关于键(),&quot;&quot;,{}等的语法...
英文:

I have this:

cat &gt; ~/add_api_txt_hook.sh &lt;&lt;EOF 
#!/bin/bash 
... 
echo $MY_ENV_VAR
EOF

MY_ENV_VAR is not set when this file is made. So it makes it "" in the file.

I want the file contents to be

#!/bin/bash 
... 
echo $MY_ENV_VAR

NOT:

#!/bin/bash 
... 
echo &quot;&quot;

How do I print the actual ENV VAR KEY to the file? I have searched the internet, but it only returns how to print the value to the file.

Tried google and various syntax around the key (), "", {} etc...

答案1

得分: 2

有几种方法可以实现这个。显然,正如SiKing指出的那样,你可以用反斜杠转义美元符号。

你也可以引用 EOF 本身。例如:

$: cat &gt;x &lt;&lt;EOF
echo $PATH
EOF

$PATH(包括空值,在你的情况下)放入文件中,

$: cat &gt;x &lt;&lt;&#39;EOF&#39;
echo $PATH
EOF

则不会:

$: cat x
echo $PATH

同样,你可以使用“here-string”:

$: cat &lt;&lt;&lt;&#39;echo $PATH&#39;
echo $PATH

但要注意,无论是单引号还是双引号,here-doc 的行为基本相同 -

$: cat &lt;&lt;&quot;EOF&quot;
echo $PATH
EOF
echo $PATH

here-string 有所区别;单引号不会扩展变量,而双引号会。

$: cat &lt;&lt;&lt;&quot;echo $PATH&quot;
echo /c/Users/....(已编辑)
英文:

There are several ways to accomplish this.
Obviously, as SiKing pointed out, you can just backslash-escape the dollar sign.

You can also quote the EOF itself. While

$: cat &gt;x &lt;&lt;EOF
echo $PATH
EOF

puts the value of $PATH (including being empty, as in your case) in the file,

$: cat &gt;x &lt;&lt;&#39;EOF&#39;
echo $PATH
EOF

does not:

$: cat x
echo $PATH

Likewise, you can use a "here-string":

$: cat &lt;&lt;&lt;&#39;echo $PATH&#39;
echo $PATH

But be aware that where a here-doc behaves much the same whether single- or double-quotes are used -

$: cat &lt;&lt;&quot;EOF&quot;
echo $PATH
EOF
echo $PATH

here-strings differentiate; single-quotes don't expand variables, but doubles do.

$: cat &lt;&lt;&lt;&quot;echo $PATH&quot;
echo /c/Users/....(redacted)

huangapple
  • 本文由 发表于 2023年6月28日 23:54:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76574848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定