我正在尝试在 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/