env can be used to print the environment variables or pass environment variables to a utility/command without setting them in the current shell session.
env without any argument and see what happens.
It simply prints all the environment variables in the current session. You can also run
env with various options.
- -i: Runs a command with only specified environment variables and clears all the environment variables already set.
- -u: Runs a command by removing the specified environment variables while keeping the other values intact.
- -v: Prints the verbose output for each step of processing done by the env utility.
Let's try to print the environment variables inside a python script by passing it via the
env. You can choose to run in any language of your choice.
import os print(os.getenv('BLOG')) print(os.getenv('PATH'))
We will use
env -i /usr/local/bin/python3 main.py to run our python script. You can't use the simple python command to run the code as the
PATH value which specifies the binary path for executable will also be reset. The output should be as below.
$ env -i /usr/local/bin/python3 main.py None None
As you can see in the above output that all the values are set to
None because we have used the option
-i. Even the system PATH variable is set to
Now let's run this
env -i BLOG=hashnode /usr/local/bin/python3 main.py in the terminal.
$ env -i BLOG=hashnode /usr/local/bin/python3 main.py hashnode None
In the above output, you can see that we have set the
BLOG=hashnode and it gets printed in the output.
You can also use
-u to unset certain environment variables.
import os print(os.getenv('HOME')) print(os.getenv('SHELL'))
We will use this
env -u HOME /usr/local/bin/python3 main.py command to run the above code. Its output looks like this. You can see that
HOME doesn't get printed while the
SHELL value does.
$ env -u HOME /usr/local/bin/python3 main.py None /bin/zsh
To print more verbose output of the
env command and it's step. You can pass
-i as an option.
$ env -v -u HOME /usr/local/bin/python3 main.py #env unset: HOME #env executing: /usr/local/bin/python3 #env arg= '/usr/local/bin/python3' #env arg= 'main.py' None /bin/zsh
You can use
env in various scenarios like while debugging local code as well as some production issues to see the effect of each and every environment variable on your code or service.
If you liked this post please share it with others so that it can help them as well. You can tag me on Twitter @imumesh18. Also please follow me here and on Twitter for future blogs which I write over here