## Monday, November 16, 2009

### C & Bash frankensources

Heh, I stumbled upon an amusing overlap in C preprocessor syntax and shellscript comments. You can piggyback a C program onto a shell script, so that it's both possible to compile the file with a C compiler, and let bash evaluate it.

#if 0
echo "Hello from bash!"
exit
#endif
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
puts("Hello from C!");
return EXIT_SUCCESS;
}

Note that it's not possible to put a shebang in the beginning of the script (or other shell script comments) and compile it, as that upsets the preprocessor.

$sh frankenscript.sh.c Hello from bash!$ gcc frankenscript.sh.c -o test
$./test Hello from C! You could also have the script, when run as bash code, compile it self as C sources and run the result. #if 0 file=mktemp gcc -o$file $0$file
rm $file exit #endif #include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[]) { puts("Hello from C!"); return EXIT_SUCCESS; } ...$ sh frankenscript2.sh.c
Hello from C!
\$

Don't get me wrong, it's a perverse crime against nature and should never be used, but still, an amusing diversion.