2

I would like to use heredoc in a zsh alias, for example:

alias runthing="cd ~; date << HERE
date
HERE"

However every time I run this alias, the shell acts as if I have not terminated the heredoc, and displays this:

➜  ~ runthing
heredoc>

Entering here at the heredoc> line finishes the command, although I do not want to do this, thus the alias. I am using oh-my-zsh if that is making any difference.

How do I use heredoc correctly in a zsh alias?

  • 2
    Hello and welcome! It's unclear which shell are you using. Zsh or Bash? I just tried it with bash and it works on my system (well, you have a typo, should be alias runthing=... and not alias=runthing=... in bash). – Mr Shunz Sep 18 '18 at 10:21
  • 1
    @MrShunz, the heredoc> secondary prompt is proof that it is zsh. I've edited the question to remove the confusing references to bash. – Stéphane Chazelas Sep 18 '18 at 10:57
2

The here doc delimiter has to be a delimited line in the alias in zsh (it does look like a bug as you do add that delimiter when you press enter), so:

alias runthing='cd; date << HERE
date
HERE
'

Here, using an alias is wrong though. Consider for instance:

echo foo || runthing

Because alias is just a form of code text substitution (aliases is before all a csh feature, csh had no functions), that becomes

echo foo || cd; date...

Which means date would be run even though echo was successful.

You'd better use a function here:

runthing() {
  cd && date << EOF
date
EOF
}

(of course, it makes little sense to feed a heredoc to date given that date doesn't read its stdin, I just assume, it was only for the example).

  • Yep date was just an example! This worked perfectly, thanks! – Brian Hamill Sep 19 '18 at 9:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.