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

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

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

问题

  1. 我有这个:

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

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

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

  1. 而不是:

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

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

I have this:

  1. cat &gt; ~/add_api_txt_hook.sh &lt;&lt;EOF
  2. #!/bin/bash
  3. ...
  4. echo $MY_ENV_VAR
  5. 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

  1. #!/bin/bash
  2. ...
  3. echo $MY_ENV_VAR

NOT:

  1. #!/bin/bash
  2. ...
  3. 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 本身。例如:

  1. $: cat &gt;x &lt;&lt;EOF
  2. echo $PATH
  3. EOF

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

  1. $: cat &gt;x &lt;&lt;&#39;EOF&#39;
  2. echo $PATH
  3. EOF

则不会:

  1. $: cat x
  2. echo $PATH

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

  1. $: cat &lt;&lt;&lt;&#39;echo $PATH&#39;
  2. echo $PATH

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

  1. $: cat &lt;&lt;&quot;EOF&quot;
  2. echo $PATH
  3. EOF
  4. echo $PATH

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

  1. $: cat &lt;&lt;&lt;&quot;echo $PATH&quot;
  2. 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

  1. $: cat &gt;x &lt;&lt;EOF
  2. echo $PATH
  3. EOF

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

  1. $: cat &gt;x &lt;&lt;&#39;EOF&#39;
  2. echo $PATH
  3. EOF

does not:

  1. $: cat x
  2. echo $PATH

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

  1. $: cat &lt;&lt;&lt;&#39;echo $PATH&#39;
  2. echo $PATH

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

  1. $: cat &lt;&lt;&quot;EOF&quot;
  2. echo $PATH
  3. EOF
  4. echo $PATH

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

  1. $: cat &lt;&lt;&lt;&quot;echo $PATH&quot;
  2. 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:

确定