Bash to Zsh: Allowing Comments in Interactive Shells

This entry is part 5 of 6 in the series Bash to Zsh

As I continue my move from Bash to Zsh at Apple’s strong suggestion I continue to bump into little differences that cause me minor problems. Today it was the fact that while Bash treats comments as comments even when they’re entered in an interactive shell, Zsh does not, at least not by default on MacOS.

TL;DR – setopt INTERACTIVE_COMMENTS

I have commands saved as Evernote notes and/or TextExpander snippets that contain comments for context or explanation. This is not a real example, but it illustrates the point.

The curl command to get a single-line version of my local weather from the CLI is:

curl 'http://wttr.in/Maynooth?format=3&m'

That’s pretty cryptic! Sure, it’s obvious how to specify the city, but what does format=3 mean? And while we’re at it, why does the URL end in &m?

There wouldn’t be much point in saving a snippet like that in TextExpander or Evernote without an explanation for those parameters. That’s why I’d save that command like so:

curl 'http://wttr.in/Maynooth?format=3&m' # format 3 for single line & m for metric

I can copy/paste or expand that command into Bash and it will execute perfectly and dutifully ignore the comment. When I tried a similar command in Zsh this morning things didn’t go so well! Instead of ignoring my comment Zsh tried to interpret it as a command, something it failed miserably at!

When this happened my first thought was that Zsh used a different syntax for comments, but that didn’t seem likely since I’ve read over and over again that most Bash shell scripts work just fine in Zsh. That seems impossible if the comment syntax is different.

What’s really going on here is much more subtle — when executing shell command non-interactively (i.e. while executing a script) Zsh does ignore comments, but it doesn’t ignore them when you run Zsh as an interactive shell. I honestly don’t understand why anyone would think that was a good idea! I should be able to copy-and-paste a command from a Zsh shell script into a Zsh shell and have it behave the same way, but I can’t if the line from the script contains a comment. Sorry, but the only word I can think of to describe that is ‘dumb’!

Thankfully there is a fix — Zsh proves an option named INTERACTIVE_COMMENTS which instructs the shell to ignore comments in interactive shells. This option can be enabled with the command setopt INTERACTIVE_COMMENTS.

To fix this issue in all your interactive Zsh shells, add lines like the following to your ~/.zshrc file:

# allow comments in interactive shells (like Bash does)
setopt INTERACTIVE_COMMENTS