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 " [...]"
sudo env VAR1="DEF" sh -c '...'may be less trouble -- you don't need to worry about making your definitionseval-safe, which is certainly a concern if you're trying to pass data from untrusted sources to a script running with escalated privileges. Though of course that doesn't solve the problem of double quotes causing early expansion -- you do indeed need to use single quotes for your script (same as withoutsudo;sh -c "foo=bar; echo $foo"is always broken,sudoor no).