Why can't "echo" command print environment variables?

I needed some random numbers, so I used $RAMDOM to generate it :

 use std::process::Command;

 let output = Command::new("echo")
            .arg("$RANDOM")
            .output()
            .expect("Failed to get random");
  let content = String::from_utf8(output.stdout).unwrap();
  
  println!("Get Random value : {}", content);

but the output is like this :

Get Random value : $RAMDOM

Get Random value : $RAMDOM

I execute "echo $RANDOM" in shell and it could get correct random number.

It looks like "$RAMDOM" is just recognized as a string. How can i get it by the echo command?

The $RANDOM thing isn't a feature of echo but rather is a feature of the shell you use, for example bash, zsh, fish, etc. The shell expands the $RANDOM into a string corresponding to what the (environment) variable RANDOM holds. If you want to achieve the same effect, invoke the shell in the command:

 let output = Command::new("bash")
            .args(&["-c", "echo $RANDOM"])
            .output()
            .expect("Failed to get random");
  let content = String::from_utf8(output.stdout).unwrap();
  
  println!("Get Random value : {}", content);

This effectively execute bash -c "echo $RANDOM".

6 Likes

(It's magic shell variable and not an environment variable at all (unless you override it).)

More generally, variable expansion is a shell thing, where as Command results in a system call (at the OS level). Also, not all shell variables are exported to the environment (even when talking about non-magic variables).

Consider using a crate for generating random numbers.

5 Likes

Note that when running a shell, you must always take care to not accidentally expose any user input to the shell as this can cause security issues. Compare this code in python:

% python3
>>> import os
>>> name = "zfc1996"
>>> os.system("echo Hello " + str(name))
Hello zfc1996
0
>>> name = "`rm /tmp/deletes_this_file`"
>>> os.system("echo Hello " + str(name))
rm: /tmp/deletes_this_file: No such file or directory
Hello
0

I.e. this program will delete a file (or do worse things) if the variable name contains malicious input.

5 Likes

Aside from your question, if you do need random numbers in Rust, look at the rand crate - it has a good set of well thought through ways to make use of randomness in your Rust code.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.