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.
In answer to your first question, there’s no parameter substitution because you’ve put the delimiter in quotes – the bash manual says:
If you change your first example to use
<<EOFinstead of<< "EOF"you’ll find that it works.In your second example, the shell invokes
sudoonly with the parametercat, and the redirection applies to the output ofsudo catas the original user. It’ll work if you try: