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!")
#"""