PolyglotShellScripts

Created sobota 16 maja 2020

Sometimes it's useful to run a little shell script before allowing an interpreter or a compiler to work on a file. The script may help find a correct interpreter or compile and run the resulting binary.

Rules: virtually transparent for normal interpreter/compiler and prepend only.

Python


Python will not care about stray strings. However shell will evaluate them as commands.

Try to find one of: python3.7, python3 or python to run the script.

"set" "-e"
"exec" "$(for p in python3.7 python3 python; do which p && break; done)" "$0" "$@"

Make


Slash-escaped newlines work as a line continuation also for comments in a Makefile, unlike in shell.

Run make from PATH (it may be in other place then /usr/bin) on the file.

#\
set -e
#\
exec make -f "$0" "$@"

C and C++


Thanks to preprocessor directives starting with a # it's very easy to just wrap around with if.

Compile and run a C file:

#if 0
set -e; [ "$0" -nt "$0.bin" ] &&
gcc -Wall -Wextra -pedantic -std=c99 "$0" -o "$0.bin"
exec "$0.bin" "$@"
#endif