How do sudo environment variables work in linux?

bash, linux

Solution

When you run `sudo echo $MYVAR`, the environment variable is expanded in your shell ... before the `sudo` command gets to see it.

When you run a script using `sudo`, that script only sees the environment variables that `sudo` has included in the environment. The default is to not to include them ... for security reasons.

The `sudo` command has an option `-E` that tells the command that the user wants to pass through all environment variables. The sudoers configuration file may or may not permit this.

Problem

I'm currently perplexed by the following: ``` sudo echo $MYVAR ``` outputs my variable from my .bashrc, but ``` sudo ./test.sh ``` does not, where test.sh is the below executable: ``` #!/bin/sh echo $MYVAR ``` I'm running Ubuntu 14.04. Can someone enlighten me as to what's going on here?

Original source