#!/usr/bin/env rdmd
import std.stdio;
void main() { writeln("This source file can act as an executable!"); }
I use Nim for academic science, and I often have a handful of small tasks that I'd rather not set up project folders / build scripts for. Is there some way I could write something like the following?
#!/usr/bin/env nimrun
echo "This source file can act as an executable!"
If this isn't available, would such an addition be accepted to the repository, to make it easier to share scripts written in Nim?
You can sort of get this working with:
#!/usr/bin/env nimrod c --verbosity:0 -r
echo "Hello Unix!"
I don't think this is a very good idea anyway because you are depending on nimrod and its standard library for each run, which means you essentially have to distribute your script + nimrod + working gcc compiler, or will have to fix whatever breaks from that brittle chain at any change. At that point, isn't it easier to distribute statically linked binaries?
You can use this utility as a starting point if you're interested.
It's untested on everything but OS X, but should work on other POSIX systems also.
gradha: At that point, isn't it easier to distribute statically linked binaries?
Such a tool is generally something that you use for small scripts, not stuff that you actually distribute.
gradha: Shebang commands with whitespace don't seem to work, unfortunately. Though you're right that native compilation is handy for distribution, but I'm also interested in, for example, handing a single file to a colleague working on Windows or OS X (I use Linux) and saying, "Just run this with Nim, and feel free to tweak the code!"
Jehan: Thanks for the link! This is exactly what I'm looking for, though I'm not so crazy about the SQLite dependency, so I might modify it to use another locking mechanism.
I'm not crazy about the SQLite dependency, either, but there's currently no file locking module in Nim. If you're interested in writing a portable file locking module (e.g. by adapting Python's or the relevant parts of Lua's LFS), I think that would be a welcome addition to the standard library.
And no standard defines how hashbang lines are to be interpreted. Operating systems have traditionally done this in one of several different ways:
Including, of course, different interpretations of what counts as "whitespace" in 1 and 2 above.
Most modern operating systems use one of the first two options above. Thus, to be portable, you want to have at most one argument separated by a space that does not contain any whitespace. In particular, if you use the #!/usr/bin/env trick, that means no arguments at all.