简体   繁体   中英

Set env variable inside sudo statement - Linux shell

I need to modify an environment variable inside a sudo statement . The sudo statement includes some instructions.

In the example, I set the environment variable VAR1 with the value "ABC".

Then, in the sudo statement (and only here), I need to change that value to "DEF". But the value did not change after I set the value to "DEF". Echo commands return "ABC" as the value of VAR1.

How can I change/set the value of the variable inside the sudo statement?

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:

#env VAR1="DEF" sudo -u <user> -E -i sh -c " [...]"

Use single quotes to prevent the outer shell from interpolating $VAR1 . You need $VAR1 to be passed to the inner shell so it can expand it.

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 .

(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

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