Project handling for command line scripts

Is there a good way to specify projects for command line Julia scripts? e.g. I have a script foo.jl that is intended to be called from the command line: how do I ensure that it gets the correct Project.toml file (which, for the time being, we assume resides in the same directory as the script), and ideally instantiate the Project if it hasn’t already?

The best I’ve come up with so far is to start my scripts with

#!/usr/bin/env julia
using Pkg
Base.ACTIVE_PROJECT[] = @__DIR__ # Pkg.activate(@__DIR__) creates an annoying message
Pkg.instantiate()

This seems like overkill (not to mention uses an internal variable). Is there a better way to do this?

4 Likes

Could you add the project to the shebang:

#!/usr/bin/env julia --project=...

?

1 Like

Here is a pattern that I use sometimes:

#!/bin/bash
# -*- mode: julia -*-
#=
JULIA="${JULIA:-julia --color=yes --startup-file=no}"
export JULIA_PROJECT="$(dirname ${BASH_SOURCE[0]})"

set -ex
${JULIA} -e 'using Pkg; Pkg.instantiate()'

export JULIA_LOAD_PATH="@"
exec ${JULIA} "${BASH_SOURCE[0]}" "$@"
=#
using Whatever
...

Ref: https://docs.julialang.org/en/latest/manual/faq/#How-do-I-pass-options-to-julia-using-#!/usr/bin/env?-1

Not sure if this is less overkill, though.

8 Likes

the challenge is specifying the project path in the shebang