Using variables inside a 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

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

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

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

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

3 Answers
3

Leave a Comment