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.
If you like the content on this site, please support it by using this link to order from Amazon. You know you were going to go there and buy stuff anyhow so why not help me pay the hosting bill.
Huh, I think you got that from me. I’ve since discovered a much better way to do it:
cat >/tmp/file.c <<_SRC
#include
int main(void) { printf(“i am a c program\n”);
_SRC
… just pretend the closing bracket is in main
Yep, I did get it from you. Dunno why I didn’t credit you =^_^= It’s a slick little trick. I’m continually amazed by all of the things you can do with a little bash script. The one advantage of the first method is that the C code stands out explicitly in the file but if you are going for maximum efficiency, your new way is definitely better.
Did you see my little writeup of your original program that you submitted to 2600? http://www.notanon.com/shell-scripts/command-line-drum-and-bass/2010/04/15/