The following build script fails to correctly write the file. What is the error?

Go & Rust interview question for Advanced practice.

Answer

The variable $OUTDIR is not expanded because it is inside a literal string passed to .arg().

Explanation

The Command API does not automatically expand environment variables within string arguments. The string "echo 'hello' $OUTDIR/hello.txt" is passed literally to sh. The shell will not expand $OUTDIR because the environment variable is not exported to the child process in a way that sh -c will use it. The correct way is to construct the command string within Rust using the outdir variable, for example: format!("echo hello {}/hello.txt", outdir).

Related Questions