retrography
retrography

Reputation: 6812

Combining heredoc and input redirection in Bash vs ZSH

The following code works on ZSH with no issue, combining the heredoc with the content of the file test.csv:

cat <<EOF <test.csv
id,name,age
EOF

How can I write the same command in Bash?

Upvotes: 1

Views: 571

Answers (2)

chepner
chepner

Reputation: 531165

In addition to @blami's answer, you can use cat twice in a command group (trading the memory needed to store all of test.csv in memory for the time it takes to run cat a second time).

{
  cat <<EOF
  id,name,age
EOF

  cat test.csv
}

or, since the here document is so short, use a process substitution (which still forks another process):

cat <(echo "id,name,age") test.csv

Upvotes: 5

blami
blami

Reputation: 7411

$(<file) will work in both Bash and Zsh:

cat <<EOF
id,name,age
$(<test.csv)
EOF

It will also work in Ksh (from where I believe it comes and was ported to Bash and Zsh). It behaves as $(cat file) except it will not call out to cat and will be handled completely by the shell itself.

It is described in Bash documentation Command Substitution section:

The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).

Upvotes: 5

Related Questions