Tip: Make an executable script from a Julia file

Richard Anaya
May 8 · 1 min read

Sometimes small details make us feel good. Those who use Julia might know the classic

julia -e "println(\"hello\")"

Let’s say I wanted to put this into a script for me to execute from a terminal, it’d be kind of messy to put in a script file as is.

Let’s create file called “hello” (note no .jl ending).

exec julia -O3 "$0" -- $@

Looks kind of weird, but this is both a valid script and a valid Julia program! It’s a script that executes it’s own file and passes the arguments to it.

“#” is a normal bash comment and a julia comment

“#=” is the start to a julia multiline comment

“exec” calls julia and replaces the shell with the process meaning we don’t try to execute anything after

“-O3" gives julia maximum optimization

When exec finally does get called, the top four lines of the file are instantly ignored because of valid Julia comments and the rest executes as expected.

./hello abc 123

gives us

["abc", "123"]

Windows can do the same trick with a hello.bat file

@echo off
call julia -O3 "%0" -- %*
goto :eof

Have fun!