In Bash shell, I want to sanitize the environment as the first thing when running with a command.
I want to unset all the environment variables and only set the ones that are critical for the shell to function, plus the ones the ones needed by my script to complete it's task.
Is there a way to do this in a simple and clean way?
In order to set a permanent environment variable in Bash, you have to use the export command and add it either to your “. bashrc” file (if this variable is only for you) or to the /etc/environment file if you want all users to have this environment variable.
You can use env
and a wrapper script:
#!/bin/bash env -i /path/to/main_script.sh
From man env
:
-i, --ignore-environment start with an empty environment
You can also, of course, just run the script as env -i script.sh
if you are running it by hand. Unfortunately as far as I can tell one can't use the script shebang to run bash
through env
like this; the shebang can only accept two parameters by definition as parsed by the kernel.
The other semi-reliable solution using env
or exec -c
(which does pretty much the same) that I can think of would be to use exec -c $0
to re-run the script with a clean environment if you detect it's not clean. Assuming $HOME
is set in an unclean environment and is not set in a clean one (that's true in my install):
#!/bin/bash [ "$HOME" != "" ] && exec -c $0 # rest of the script here
Command: env -i bash
Example, create local and environment variables, then reset to defaults:
el@defiant ~$ LOCAL_DOGE="such variable" el@defiant ~$ ENVIRONMENT_DOGE="much code" el@defiant ~$ export ENVIRONMENT_DOGE el@defiant ~$ set | grep DOGE ENVIRONMENT_DOGE='much code' LOCAL_DOGE='such variable' el@defiant ~$ env | grep DOGE ENVIRONMENT_DOGE=much code el@defiant ~$ env -i bash el@defiant ~$ set | grep DOGE el@defiant ~$ env | grep DOGE el@defiant ~$
So wow, LOCAL_DOGE
and ENVIRONMENT_DOGE
are gone with one command.
env - /bin/bash
Example:
el@defiant ~$ DOGE1="one" el@defiant ~$ export DOGE2="two" el@defiant ~$ set | grep DOGE DOGE1=one DOGE2=two el@defiant ~$ env | grep DOGE DOGE2=two el@defiant ~$ env - /bin/bash el@defiant ~$ set | grep DOGE el@defiant ~$ env | grep DOGE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With