This is a nifty trick you can use to impress your friends. Imagine you have some smallish program that you want to wrap up into a single file for simplicity. Part of final output perhaps relies on a clever bit of shell scripting and another part relies on a binary of some sort that you need to get the job done. Here’s a way to wrap it all up in a tidy little package:
#!/bin/sh
grep SRC: $0 | grep -v “grep SRC:” | sed -e s/SRC://g > /tmp/hello.c
gcc -o hello /tmp/hello.c
./hello
exit
SRC: #include <stdio.h>
SRC: int main(int argc, char *argv[])
SRC: {
SRC: printf(“Hello World\n”);
SRC: return 0;
SRC: }
Everything below exit is completely ignored by your shell. The grep statement goes through the shell script line by line and returns the all the lines starting with “SRC: ” to sed. Sed uses a simple regex to strip the “SRC: ” off your source code and sends the output to a file in your /tmp directory. Then the file is compiled and ran. You could go further and delete the source file out of the /tmp directory if you like or don’t bother.