Skip to content

Comment on Scriptisto: "Shebang interpreter" that enables writing scripts in compiled langs

Comments

I prefer to take advantage of the fact that without a proper shebang the file will be first executed by the shell. Then it is easy to do almost whatever you want.

For example I put this in front of my test C files:

  #if 0
  set -e; [ "$0" -nt "$0.bin" ] &&
  gcc -Wall -Wextra -pedantic -std=c99 "$0" -o "$0.bin"
  exec "$0.bin" "$@"
  #endif
I call those: polyglot shell scripts. All my examples are valid files for the language while working as shell scripts at the same time.

In the past when Python 3 was still not obviously there and under different names it was once useful for me to have this on top of a python script:

  "set" "-e"
  "exec" "$(for p in python3.7 python3 python; do which p && break; done)" "$0" 
  "$@"
It works, because Python doesn't care about stray strings.

You can also use the trick with Makefiles, although I never needed to use it:

  #\
  set -e
  #\
  exec make -f "$0" "$@"
This is not a useful example, but it works. This works, because make will treat slash followed by a new-line as a comment continuation and bash will ignore it.
I prefer to take advantage of the fact that without a proper shebang the file will be first executed by the shell

I know that bash does this, and possibly other shells, but it doesn't work in general when you `execv` the file (or when using the subprocess API on python f.i). But cool trick anyway

I appreciate a good hack more than most, but this is the kind of cleverness which makes life hell for anyone else who needs to understand what the fuck is happening and why.

At least with TFAs shebang at the top of the file, it kind of gives a clue. Upon reflection, I don't feel great about either way, haha. Even if it makes sense to me, it'll be a little too sneaky for most.

A few lines of comment can make the trick

For the sweet and rare soul who bothers to document it, absolutely.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.