使用一个bash定界符内的变量 [英] Using variables inside a bash heredoc

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

问题描述

我想插一个bash定界符内的变量:

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的发球,因为创建该文件需要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

没有参数扩展,命令替换,算术扩展,或
  路径扩展上的的执行。如果的字的任何字符的是
  报价时,的分隔符的是引用删除对词的结果,而
  此处,文档中的行不会被扩展。如果的的是不带引号的,所有的
  此处文档的行受到参数扩展,命令替换和算术扩展。 [...]

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. [...]

如果你改变你的第一个例子中使用&LT;&LT; EOF 而不是&LT;&LT; EOF,你会发现,它的作品。

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

在你的第二个例子中,外壳调用须藤只在参数,重定向适用于 sudo的猫作为原始用户的输出。如果你尝试它会工作:

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定界符内的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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