英文:
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*** 打印到文件中?我在互联网上搜索过,但它只返回如何将值打印到文件中的方法。
尝试了谷歌和各种关于键(),"",{}等的语法...
英文:
I have this:
cat > ~/add_api_txt_hook.sh <<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 ""
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 >x <<EOF
echo $PATH
EOF
将 $PATH
的值(包括空值,在你的情况下)放入文件中,
$: cat >x <<'EOF'
echo $PATH
EOF
则不会:
$: cat x
echo $PATH
同样,你可以使用“here-string”:
$: cat <<<'echo $PATH'
echo $PATH
但要注意,无论是单引号还是双引号,here-doc 的行为基本相同 -
$: cat <<"EOF"
echo $PATH
EOF
echo $PATH
here-string 有所区别;单引号不会扩展变量,而双引号会。
$: cat <<<"echo $PATH"
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 >x <<EOF
echo $PATH
EOF
puts the value of $PATH
(including being empty, as in your case) in the file,
$: cat >x <<'EOF'
echo $PATH
EOF
does not:
$: cat x
echo $PATH
Likewise, you can use a "here-string":
$: cat <<<'echo $PATH'
echo $PATH
But be aware that where a here-doc behaves much the same whether single- or double-quotes are used -
$: cat <<"EOF"
echo $PATH
EOF
echo $PATH
here-strings differentiate; single-quotes don't expand variables, but doubles do.
$: cat <<<"echo $PATH"
echo /c/Users/....(redacted)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论