简体   繁体   中英

How can I support comments when eval'ing a file to set environment variables for a single command?

I'm working on a project with a file variables.env and add VAR_THREE and comment it as follows:

VAR_ONE=val1
VAR_TWO=val2

# comment the purpose of the new variable
VAR_THREE=val3

From the command line I run this to set the variables and launch the program (run via an existing shell script in the project):

eval $(cat variables.env) java -jar my.jar

The comment seems to apply to everything afterwards including the java command, evident by checking echo $VAR_THREE does not have a value and I get no output from my .jar. If I leave my comment out of variables.env VAR_THREE is set and the program runs and produces output.

Is there a way to allow comments in the variables file without it applying to subsequent lines and commands?

The easy thing is to use a subshell.

(set -a; . variables.env; exec java -jar my.jar)

To break this down into its component parts:

  • ( ... ) puts the entire code inside a subshell -- a copy of the shell created with fork() but no exec -family call -- so none of the variables will persist past its completion.
  • set -a tells the shell to automatically export any variables to the environment (so they'll be visible to the java subprocess). Because of the subshell, this is still limited in scope to the code run here.
  • . variables.env . variables.env is a more portable equivalent to source variables.env , running the contents of variables.env as a script.
  • exec tells the already-existing subshell to replace itself with the java executable. Without exec (and absent some scenario-specific/undocumented runtime optimizations), running an external command creates a new subshell, tells that new subshell to replace itself with the java executable, and then waits for the new subshell to exit; by running exec java , we consume the subshell we already made, rather than creating a second one.

...and as an extra benefit, you don't get the undesired side effects of eval (causing an extra pass of string-splitting, glob expansion, and other potential confusion when passing arguments that contain whitespace or other syntax-sensitive characters).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM