Useful Julia script tips? (workaround shebang)

I found a useful little hack so I share it here. It may already be discovered elsewhere, but it’s fun to re-discover a nice(?) trick!

If you ever tried to write a julia script and put its options in the shebang, you might notice that #!/usr/bin/env does not work well with options (depending on OS). Of course, you can write a small wrapper in a separate file. But if you want to do it in one file, you can also do:

#!/bin/bash
# -*- mode: julia -*-
#=
exec julia --color=yes --startup-file=no "${BASH_SOURCE[0]}" "$@"
=#

Base.banner()  # put any Julia code here

Anything between the first #= and exec will be executed as the normal bash command. You can do anything there, like setting up environment variables.

Another tip: In Julia 1.x, you can’t catch InterruptException in the script. However, it is actually capturable in -e ... context. So, as a workaround, you can do:

#!/bin/bash
# -*- mode: julia -*-
#=
exec julia --color=yes --startup-file=no -e "include(popfirst!(ARGS))" "${BASH_SOURCE[0]}" "$@"
=#

@show ARGS
try
    println("sleeping...")
    sleep(10)
catch err
    @show err
finally
    println("woke up")
end

Of course, similar multi-language comment hack works between Python and Julia:

#!/usr/bin/env python
# -*- mode: julia -*-
#=

print("hello from Python!")

import os
cmd = ["julia", __file__]
os.execvp(cmd[0], cmd)

"""
=#

println("hello from Julia!")

#"""
12 Likes

Very neat, thanks! It would be great if the manual had a short section on shebang scripts & Julia, possibly including the above information.

I just sent a PR to include the documentation for SIGINT behavior: https://github.com/JuliaLang/julia/pull/29411

I can send another PR for the “shebang” part. I thought maybe this is too hacky for an official documentation, but let’s see… Not sure where to put, though. https://docs.julialang.org/en/latest/manual/workflow-tips/? https://docs.julialang.org/en/latest/manual/faq/?

1 Like

IMO it should go in Getting started somewhere, since that is the section that talks about running Julia. Could probably be renamed to “Running Julia” too.

1 Like

Here it goes https://github.com/JuliaLang/julia/pull/29423

2 Likes