Skip to content

Instantly share code, notes, and snippets.

@ytaki0801
Last active January 23, 2023 02:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ytaki0801/d3a427feaa3ed3ca99cdd96c465db0ca to your computer and use it in GitHub Desktop.
Save ytaki0801/d3a427feaa3ed3ca99cdd96c465db0ca to your computer and use it in GitHub Desktop.
Brainf**k interpreter in POSIX shell
#!/bin/sh
while IFS= read L; do
T=$T$L
done < "$1"
L=0
while [ "$T" ]; do
case $T in
+*) export "C$L"=0 L=$((L+1));;
-*) export "C$L"=1 L=$((L+1));;
\>*) export "C$L"=2 L=$((L+1));;
\<*) export "C$L"=3 L=$((L+1));;
.*) export "C$L"=4 L=$((L+1));;
,*) export "C$L"=5 L=$((L+1));;
\[*) export "C$L"=6 L=$((L+1));;
\]*) export "C$L"=7 L=$((L+1));;
esac
T=${T#?}
done
P=0
while [ $P != 16384 ]; do
export "A$P"=0
P=$((P+1))
done
N=0
P=0
while [ $N != $L ]; do
case $((C$N)) in
0) export "A$P"=$((A$P+1));;
1) export "A$P"=$((A$P-1));;
2) P=$((P+1));;
3) P=$((P-1));;
4) printf "$(printf '\\%o' $((A$P)))";;
5) stty -icanon
D=$(dd bs=1 count=1 2>/dev/null)
export "A$P"=$(printf '%d' \'$D)
stty icanon;;
6) case $((A$P)) in
0) D=1
while [ $D != 0 ]; do
N=$((N+1))
case $((C$N)) in
6) D=$((D+1));;
7) D=$((D-1));;
esac
done;;
*) ;;
esac;;
7) case $((A$P)) in
0) ;;
*) D=1
while [ $D != 0 ]; do
N=$((N-1))
case $((C$N)) in
6) D=$((D-1));;
7) D=$((D+1));;
esac
done;;
esac;;
esac
N=$((N+1))
done
@ytaki0801
Copy link
Author

ytaki0801 commented Jan 22, 2023

An example in Debian GNU/Linux 11 x86_64 with dash 0.5.11:

$ cat primes.bf
>++++[<++++++++>-]>++++++++[<++++++>-]<++.<.>+.<.>++.<.>++.<.>------..<.>.++.<.>--.++++++.<.>------.>+++[<+++>-]<-.<.>-------.+.<.>-.+++++++.<.>------.--.<.>++.++++.<.>---.---.<.>+++.-.<.>+.+++.<.>--.--.<.>++.++++.<.>---.-----.<.>+++++.+.<.>.------.<.>++++++.----.<.>++++.++.<.>-.-----.<.>+++++.+.<.>.--.>++++++++++.
$ dash bf-intp.sh primes.bf
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment