How to insert a # via \immediate\write18 within a macro

Since macros are expanded in a \write, I'd have

\edef\shebang{\string#!/bin/bash}

in the preamble so that you can use

\newcommand{\CreateBashScript}{%
    \immediate\write18{echo "\shebang" > \jobname.command}%
}

in the command.

As told in the comment, you could also double the # in the replacement text

\newcommand{\CreateBashScript}{%
    \immediate\write18{echo "\string##!/bin/bash"  > \jobname.command}%
}

but I believe that \shebang is clearer.


I fought with this problem for two days now and came across this great answer a thousand times before I understood its relevance. Therefore I attempt to reformulate it, stripped to its essence:

If you want to write out a literal # into some file, you can do something like

\newcommand{\writeouthash}{%
  \immediate\write\myfile{\string##}%
}