bash - 在 bash heredoc 中使用变量

标签 bash variables sh heredoc

我正在尝试在 bash heredoc 中插入变量:

var=$1
sudo tee "/path/to/outfile" > /dev/null << "EOF"
Some text that contains my $var
EOF

这并没有像我预期的那样工作($var 按字面意思处理,没有展开)。

我需要使用 sudo tee 因为创建文件需要 sudo。做类似的事情:

sudo cat > /path/to/outfile <<EOT
my text...
EOT

不起作用,因为 >outfile 在当前 shell 中打开文件,该 shell 未使用 sudo。

最佳答案

在回答您的第一个问题时,没有参数替换,因为您已将定界符放在引号中 - the bash manual says :

The format of here-documents is:

      <<[-]word
              here-document
      delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. [...]

如果您将第一个示例更改为使用 <<EOF而不是 << "EOF"你会发现它有效。

在您的第二个示例中,shell 调用 sudo仅使用参数 cat ,重定向适用于 sudo cat 的输出作为原始用户。如果您尝试,它会起作用:

sudo sh -c "cat > /path/to/outfile" <<EOT
my text...
EOT

关于bash - 在 bash heredoc 中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52568684/

相关文章:

bash - 如何在设置别名时转义单引号

linux - 如何通过 popen() 将参数传递给我的 c 程序中的 bash 脚本?

performance - 我应该养成删除 R 中未使用的变量的习惯吗?

command-line - 如何为 shell 命令设置环境变量

php - 安装 Composer 时出错 - curl : (23) Failed writing body (0 ! = 16133)

bash - 如何限制 bash 脚本中运行的命令数量?

php - 包含文件中的函数变量 - php

javascript - 局部函数变量更改不会影响全局范围内的变量。为什么不?

bash - 和有什么不一样?和 Bash 中的 *?

bash - 在 while 循环内修改的变量不会被记住