"Source" shell script


#1

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?


#2

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


#3

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.


#4

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.)


#5

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.


#6

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"
printenv

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


#7

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


#8

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.)


#9

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).


#10

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