call a shell script from another shell script via sudo - environment variables? call a shell script from another shell script via sudo - environment variables? shell shell

call a shell script from another shell script via sudo - environment variables?


As @geekosaur mentioned, sudo resets the environment for security reasons.To preserve the environment pass -E switch to sudo.

from the sudo manpage:

-E

The -E (preserve environment) option indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the -E option is specified and the user does not have permission to preserve the environment.


The problem here is not with the shell script, but that for security reasons sudo sanitizes the environment it passes to the program it runs. See man sudoers for details, and /etc/sudoers on your system for what (if any) environment variables it will preserve.


If you want to keep only a specific set of variables (rather than all of them) for reasons of security or simplicity, you can simply assign them as part of the sudo command:

$ cat test.sh #!/usr/bin/env bashecho "$foo"$ unset foo$ foo=bar ./test.shbar$ sudo foo=bar ./test.shbar