macosrustreleasedotenv.env

Using .env file with release binary


When building a rust binary with cargo build --release, the binary is perfectly generated inside /target/release, however I get a message that it cannot load env variables.

I then copied the .env file from the project to the same directory and I still get the error.

Inside the code it looks like this:

use dotenv::dotenv;

async fn main() -> anyhow::Result<()> {
    dotenv().ok();

    let my_env_var= std::env::var("MY_ENV_VAR").expect("MY_ENV_VAR must be set.");
    ...
}

And of course it works perfectly fine with cargo run.

How could I run the generated binary and ensure that .env file is read correctly? (using a mac mini)

NB: I use open {binary name} to open the binary


Solution

  • As I said in comments, I think open messes with the working directory. I don't know why, and what it does exactly (some macos expert can elaborate on this), but it shouldn't matter. That's because Rust produces an executable binary. This means you don't need to do

    open {binary name}
    

    you can simply do

    {binary name}
    

    in terminal and it should work without any issues.