Comment

Comment by hawski

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.
parent hawski 2 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton