"Source" shell script

I have a shell script and I would like to “source” it from rust. That is I need to run commands from rust in an environment that looks like the result of source myscript.sh. How to accomplish this?

Does any language allow this? It seems like you’d have to emulate the entire shell language!

1 Like

Wow I don’t know enough about how processes and the shell to answer this, but it surprises me that you would have to emulate the shell and can not trick it into doing the work.

You could invoke the shell externally, but source is used to affect the current shell – setting variables (which may or may not be exported as environment variables), defining shell functions, aliases, etc. Only the environment variables make obvious sense to pull into a Rust process, but I don’t know any easy way to do that. (A hard way would be to act like a debugger and read the shell’s environment before it exits.)

1 Like

There is https://github.com/shelljs/shelljs which seems related? I haven’t used it but I know that npm users use it in scripts a lot.

Okay a quick and dirty way to read the environment “before exit” would be to wrap the shell script in another script

source myscript.sh
echo "here comes the environment"

and run that. Is there a cleaner way that does not need an axillary script?

Hmm, that wrapper could be a direct string: sh -c "source myscript.sh && printenv"


Thanks for all your help! Now that I know my options, I think I will port the parts of the script that manipulate environment variables to rust instead. (Its also not ideal, since the script is maintained by somebody else and could in principle change over time.)

Don’t use this, but just for giggles: https://play.rust-lang.org/?gist=a48cf8561a904583afd7f766e93ac7d3&version=stable&mode=debug (using stdin for the script since it doesn’t look like the playground lets you create files).

1 Like

Wow very clever how you made this work in the playground!