[英]Set env variable inside sudo statement - Linux shell
I need to modify an environment variable inside a sudo statement . 我需要在sudo语句中修改环境变量。 The sudo statement includes some instructions.
sudo语句包含一些说明。
In the example, I set the environment variable VAR1 with the value "ABC". 在示例中,我将环境变量VAR1设置为值“ ABC”。
Then, in the sudo statement (and only here), I need to change that value to "DEF". 然后,在sudo语句中(仅在此处),我需要将该值更改为“ DEF”。 But the value did not change after I set the value to "DEF".
但是,将值设置为“ DEF”后,该值没有更改。 Echo commands return "ABC" as the value of VAR1.
回声命令返回“ ABC”作为VAR1的值。
How can I change/set the value of the variable inside the sudo statement? 如何在sudo语句中更改/设置变量的值?
Here an example of the code I run: 这是我运行的代码示例:
#!/bin/bash
export VAR1="ABC"
sudo -u <user> -i sh -c "
export VAR1="DEF";
echo $VAR1;
"
echo $VAR1;
Extra info: I tryed the option -E of sudo, to preserve the environment variable at the moment of sudo invocation (source: https://unix.stackexchange.com/questions/337819/how-to-export-variable-for-use-with-sudo/337820 ), but the result did not change: 额外信息:我尝试了sudo的-E选项,以在sudo调用时保留环境变量(来源: https : //unix.stackexchange.com/questions/337819/how-to-export-variable-for- use-with-sudo / 337820 ),但结果没有改变:
#env VAR1="DEF" sudo -u <user> -E -i sh -c " [...]"
Use single quotes to prevent the outer shell from interpolating $VAR1
. 使用单引号防止外壳插入
$VAR1
。 You need $VAR1
to be passed to the inner shell so it can expand it. 您需要将
$VAR1
传递给内壳,以便它可以扩展它。
sudo -u <user> -i sh -c '
export VAR1="DEF"
echo "$VAR1"
'
It's also a good idea to quote variable expansions to prevent globbing and splitting mishaps : write "$VAR1"
instead of $VAR1
. 引用变量扩展名也是一个好主意,以防止出现故障和分裂事故 :写
"$VAR1"
而不是$VAR1
。
(The semicolons aren't necessary since you have newlines.) (因为您有换行符,所以不需要分号。)
Try this 尝试这个
export VAR1="ABC"
sudo -u <user> -i sh -c '
export VAR1="DEF"
echo "${VAR1}"
'
echo $VAR1;
as John Kugelman pointed out, you should use ' instead of " to wrap your command to avoid shell vars interpolation. Also, when referencing to VAR
inside the command, use "${}"
instead of $
, this is what did the trick for me 正如John Kugelman指出的那样,应使用'而不是'来包装命令,以避免shell vars插值。此外,在命令中引用
VAR
时,请使用"${}"
代替$
,这就是解决问题的方法我
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.