Lighthart
Lighthart

Reputation: 3656

Shell expansion with heredoc

How does one for subshell expansion in heredoc for all command?

eg:

file=report_$(date +%Y%m%d)
cat <<EOF > $file
    date
    hostname
    echo 'End of Report'
EOF

such that all the commands are evaluated?

I am aware

file=report_$(date +%Y%m%d)
cat <<EOF > $file
    $(date))
    $(hostname)
    $(echo 'End of Report')
EOF

would work, but is there a way to specify subshell by default?

Upvotes: 3

Views: 2688

Answers (3)

Edouard Thiel
Edouard Thiel

Reputation: 6218

If you want to expand all lines as commands, heredoc is useless:

file="report_$(date +%Y%m%d)"
{
  date
  hostname
  echo 'End of Report'
} >| "$file"

You may also redirect 1> like that:

file="report_$(date +%Y%m%d)"
exec 1> "$file"
date
hostname
echo 'End of Report'

Upvotes: 1

torek
torek

Reputation: 487883

Not like that, but:

cat << EOF | sh > $file
    date
    hostname
    echo 'End of Report'
EOF

would achieve the same result. (Note that this is a new sh command—use bash if desired—and not a subshell of the current shell, so it does not have the same variables set.)

(Edit: I failed to note that this is also a UUOC: a Useless Use Of Cat; see Explosion Pills' answer. :-) )

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191729

You could use sh (or bash) as the command instead of cat; that will actually run it as shell script:

sh <<EOF > $file
    date
    hostname
    echo 'End of Report'
EOF

Upvotes: 8

Related Questions