Compiling BrainFuck with a shell script

That was easy

2020-01-20 random

BrainFuck is an esoteric programming language that is surprisingly easy to implement. It is almost on the same level as “Hello, world!”, but for compilers and interpreters. In this post, ill share my new little BrainFuck compiler I built with a bash script.

The BrainFuck instruction set

BrainFuck has 8 simple instructions:

Instruction Operation
> increment data pointer
< decrement data pointer
+ increment the byte at the data pointer
- decrement the byte at the data pointer
. print the current byte to stdout
, read one byte from stdin to the current byte
[ jump to the matching ] if the current byte is 0
] jump to the matching [ if the current byte is nonzero

The C equivalent

BrainFuck works on a “tape”. This is essentially a massive array, with a pointer that moves around. Luckily, this can be implemented with a tiny bit of C. (Thanks wikipedia)

BF C code
> ++ptr;
< --ptr;
+ ++*ptr;
- --*ptr;
. putchar(*ptr);
, *ptr=getchar();
[ while (*ptr) {
] }


Due to the fact BF has a direct conversion to C, I figured: “Why not just use sed to make a BF compiler?”. And so I did.

The script is available at, and works as follows:

  1. Create a file containing a “header” that contains some C code that imports stdio.h and creates a char array
  2. Use SED to replace all BF instructions with the matching C code
  3. Append a file footer with code to return the current value at the program pointer
  4. Compile this c file with GCC

Thank you for reading this post. If you enjoyed the content, and want to let me know, or want to ask any questions, please contact me via one of the methods listed here. If you would like to be notified about future posts, feel free to load my rss feed into your favorite feed reader, or follow me on Twitter for notifications about my work and future posts.

If you have the time to read some more, I recommend checking out one of the following posts:

Tunneling a printer from a home network to a VPN
I use a self-hosted VPN to access all my devices at all times, and to deal with my school's aggressive firewall. This post explains the process I use for exposing my home printer to the VPN.
2020 Wrap-Up
2020 has been my most productive year so far in terms of software development. This post looks back at the year
How I have tweaked my Minecraft client to be 'just right'
Over the past 10 years, I have been building the perfect Minecraft experience for myself. This post shares the collection of mods I run, and why I use them.

Made with ♥ by Evan Pratten | RSS | API Status