chr0nikler
chr0nikler

Reputation: 488

Can't access environment variable in Rust

The piece of code is as follows:

// Log in to Discord using a bot token from the environment                  
let discord = Discord::from_bot_token(                                       
    &env::var("DISCORD_TOKEN").unwrap()                                      
).expect("login failed");

I get an error saying it is unable to find the environment variable DISCORD_TOKEN.

My environment does show the variable:

myawesomename$env | grep DISCORD
DISCORD_TOKEN=you'llneverknow

If I print all the keys and values that Rust knows:

for (key, value) in env::vars() {                                            
    println!("{}: {}", key, value);                                      
}

It doesn't show the environment variable.

On a similar note, when I do env | grep CARGO, none of the CARGO variables exist, but they are printed in the Rust code.

There is something I fundamentally doesn't understand about the profile/system env variables Rust is looking at (which, I assumed, are the variables in the environment in which the process is launched).

UPDATE: I don't know what I change, but it works now. I apologize for intruding on everyone's time. Thank you for helping me look into this though.

Upvotes: 7

Views: 8615

Answers (2)

Gabriel Bento
Gabriel Bento

Reputation: 93

I know it was long ago, but in case someone is struggling with it:

In my case it was because my shell was Fish and my variable was defined in Bash.

I've presumed Rust env::var() reads whatever it finds without matter where.

So in my Fish:

set -x MY_VAR "value"

Or in Bash:

export MY_VAR="value"

Upvotes: 1

chr0nikler
chr0nikler

Reputation: 488

Undeleted this question because I got the answer. But it's because I didn't examine all the factors before asking the question.

It worked when I ran cargo run, but didn't work when I ran sudo cargo run. I was running it in sudo because I was trying to read memory of another process. The sudo profile has it's own set of env vars, and it resets the environment before going sudo.

To fix this, I ran sudo visudo and inserted this line

Defaults env_keep += "DISCORD_TOKEN'

From there, it worked.

This link got me the answer.

Upvotes: 1

Related Questions