[英]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: 我正在使用一个文件
variables.env
的项目,并添加VAR_THREE
并对其进行注释,如下所示:
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): 在命令行中,我运行它来设置变量并启动程序(通过项目中现有的shell脚本运行):
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. 此注释似乎适用于所有之后的内容,包括
java
命令,这可以通过检查echo $VAR_THREE
没有值来明显看出,而我的.jar也没有输出。 If I leave my comment out of variables.env
VAR_THREE
is set and the program runs and produces output. 如果我对
variables.env
保留我的注释, VAR_THREE
设置VAR_THREE
,程序将运行并产生输出。
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. ( ... )
将整个代码放在一个subshell内-用fork()
创建的shell副本,但是没有exec
-family调用-因此,所有变量都不会在其完成之后持续存在。 set -a
tells the shell to automatically export any variables to the environment (so they'll be visible to the java
subprocess). set -a
告诉外壳程序将所有变量自动导出到环境中(这样它们将对java
子进程可见)。 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. . variables.env
是一个更便携相当于source variables.env
,运行的内容variables.env
为脚本。 exec
tells the already-existing subshell to replace itself with the java
executable. exec
告诉已经存在的子shell用java
可执行文件替换自身 。 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; exec
(缺少某些特定于场景/未记录的运行时优化),则运行外部命令将创建一个新的子shell,告诉新的子shell用java
可执行文件替换自身,然后等待新的子shell退出; by running exec java
, we consume the subshell we already made, rather than creating a second one. exec java
,我们将使用已经完成的子shell,而不是创建第二个。 ...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). ...还有一个额外的好处,您不会得到
eval
的不良副作用(在传递包含空格或其他语法敏感字符的参数时,会引起额外的字符串拆分,glob扩展以及其他潜在的混乱) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.