Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sanitize environment with command or bash script?

Tags:

linux

bash

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?

like image 452
Otto Ulec Avatar asked Mar 12 '12 16:03

Otto Ulec


People also ask

How do I set an environment variable in Linux with bash?

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.


2 Answers

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 
like image 200
Eduardo Ivanec Avatar answered Oct 04 '22 14:10

Eduardo Ivanec


Unset all environment variables bash linux

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.

Unset all environment variables bash linux, alternate way.

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 
like image 39
Eric Leschinski Avatar answered Oct 04 '22 14:10

Eric Leschinski