2

To run Rust program with a backtrace one should set environment variable RUST_BACKTRACE to one and run the program, so my first guess as inexperienced bash user was:

$ RUST_BACKTRACE=1 && cargo run
...
note: Run with `RUST_BACKTRACE=1` for a backtrace.

but there are no backtrace in the output. So, let's check if variable is set:

RUST_BACKTRACE=1 && echo $RUST_BACKTRACE && cargo run
1
...
note: Run with `RUST_BACKTRACE=1` for a backtrace.

and finally working solution would be:

RUST_BACKTRACE=1 cargo run

Please explain to me how it works.

1 Answer 1

4

There are two possibilities how an external program sees that variable in its environment:

export it for that command

RUST_BACKTRACE=1 cargo run

In this case the variable is not part of the shell. If it was before then its value is not changed.

export it

The shell does not automatically export all its variables to programs it runs (not all shell variables are intended as part of an environment).

  1. export RUST_BACKTRACE=1
    # or
    declare -x RUST_BACKTRACE=1
    cargo run
    
  2. RUST_BACKTRACE=1
    export RUST_BACKTRACE
    # or
    declare -x RUST_BACKTRACE
    cargo run
    
  3. set -a # Each  variable  or  function that is created or modified is given the export attribute
    RUST_BACKTRACE=1
    cargo run
    
2
  • Thank you for the answer, before I accept it, I have more small question. Please, explain to me what happens with env variables when I use && to chain commands? The second example in the question makes no sense to me, why echo displays the variable, but cargo does not see it?
    – gasabr
    Commented Mar 25, 2018 at 10:44
  • @gasabr && and || have no effect on variables at all. echo does not consider its environment variables (it is not even an external command). The shell transforms echo $foo to echo bar before executing echo. The command cannot know whether there were shell variables involved. It only sees its command line arguments (not those you type but those which get executed in the end). Commented Mar 25, 2018 at 10:55

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.