HOWTO: Use the C Preprocessor in a bash script.

Sunday, September 16th, 2007

‘Ili and I came up with this today. These three magic lines run CPP over your script before executing it.

#define cpp #
cpp $0 2> /dev/null | /bin/bash; exit $?
#undef cpp

The 2> is needed because the preprocessor chokes on the shebang. Happily, bash sees CPP statements as comments, so that’s the only munging we need to do. Example usage:

#define cpp #
cpp $0 2> /dev/null | /bin/bash; exit $?
#undef cpp
#define HELLO_WORLD echo "hello, world"
HELLO_WORLD | tr a-z A-Z

which outputs:


Happy hacking! ;)


  1. Textual Pornography » Blog Archive » replied on September 16th, 2007:

    […] Colin and I came up with three lines to stick at the top of a bash script that’ll run the C preprocessor over the script before running it. See all the sordid details at his blog. […]

  2. Robert O'Callahan replied on September 16th, 2007:

    You sick, sad man.

  3. Ted Mielczarek replied on September 17th, 2007:

    You are a sick monkey. Bash scripting is bad enough as it is!

  4. Fred Wenzel replied on September 28th, 2007:

    Hah, that’s so wrong :) But I lov eit.

  5. Allan Odgaard replied on November 27th, 2007:

    As an alternative to suppressing errors and hiding cpp via a define, you can do something like the following to “skip” the first two lines of your script when feeding it to cpp:

    cat "$0"|{ read; read; cpp|/bin/bash; }; exit $?