在 bash heredoc 中使用变量 [英] Using variables inside a bash heredoc

查看:25
本文介绍了在 bash heredoc 中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to interpolate variables inside of a bash heredoc:

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

这不符合我的预期($var 按字面处理,未扩展).

This isn't working as I'd expect ($var is treated literally, not expanded).

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

I need to use sudo tee because creating the file requires sudo. Doing something like:

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

不起作用,因为 >outfile 在当前 shell 中打开文件,它没有使用 sudo.

Doesn't work, because >outfile opens the file in the current shell, which is not using sudo.

推荐答案

在回答您的第一个问题时,没有参数替换,因为您已将分隔符放在引号中 - bash 手册说:

In answer to your first question, there's no parameter substitution because you've put the delimiter in quotes - the bash manual says:

此处文档的格式为:

      <<[-]word
              here-document
      delimiter

无参数扩展、命令替换、算术扩展或对 word 执行路径名扩展.如果 word 中的任何字符是引用,分隔符是对单词的引用删除的结果,并且here-document 中的行没有扩展.如果 word 未加引号,则所有here-document 的行经过参数扩展、命令替换和算术扩展.[...]

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"你会发现它有效.

If you change your first example to use <<EOF instead of << "EOF" you'll find that it works.

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

In your second example, the shell invokes sudo only with the parameter cat, and the redirection applies to the output of sudo cat as the original user. It'll work if you try:

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

这篇关于在 bash heredoc 中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆