Delete all environment variables linux

Sanitize environment with command or bash script?

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 Bash, the env command has a flag -i which will clear all your environment variables to login default. So run this: env -i bash

That’s not really «in bash» — env is a standard UNIX command, not a bash builtin. You can invoke it without a shell at all (from C, from Python, etc).

7 Answers 7

You can use env and a wrapper script:

#!/bin/bash env -i /path/to/main_script.sh 
 -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 

I like the exec -c . At the cost of some brittleness you can strengthen it to: [ «$(env | /bin/sed -r -e ‘/^(PWD|SHLVL|_)=/d’)» ] && exec -c $0 . That is, it insists that everything be cleared except for a few things that bash seems to set automatically.

Note that by using env -i or exec , you will lose non-environment (i.e. non-exported) shell variables as well.

As for the shebang issue: coreutils’ env recently (version 8.30, released in July 2018) got an option -S which solves this issue: this option expects a string which is split on whitespaces to form the command to be called. Thus, our shebang can be written #!/bin/env -iS /bin/bash . This option even supports setting variables, so that we can preserve some variables, eg PATH and TERM: #!/bin/env -iS PATH=$ TERM=$ /bin/bash . See the documentation.

Unset all environment variables bash linux

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.

Читайте также:  Просмотр запущенных приложений linux

Unset all environment variables bash linux, alternate way.

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 

This is NOT what the OP wants imho; or else at least not a correct answer. What you do here is just a new SUBSHELL without inheriting the old environment. If you do that a few times you’ll run out of memory :p.

Agreed with Carlo, this is absolutely not a solution. it doesn’t unset variables, it starts a new session.

@JDiPierro I wrote this answer before I understood that. This answer received many upvotes because newbies hitting this stackoverflow artifact don’t know how to uniquely identify terminal identities, and this at least shows them how to get a clue. The proper followup question is: How does my operating system handle bash/zsh/shell startup sequence and shutdown sequence and how can I control it? Cheatsheet: raw.githubusercontent.com/sentientmachine/Cheatsheets/master/…

This worked when I tried it:

for c in $(set | cut -d '=' -f 1); do unset $c; done 

It spewed errors on the const variables, but I was able to ignore them.

Here is a way to do this without starting a new shell, and that will work even with weird variable names (containing whitespace/newlines):

while IFS='=' read -rd '' name value ; do unset "$name" ; done < /proc/self/environ 

The disadvantage is that it is Linux-specific, and relies on procfs being mounted.

This will unset all environment variables, even HOME and PATH . This may or may not be what you want.

Explanation: /proc/PID/environ contains the process's environment block, as a series of zero-delimited NAME=VALUE strings. We use a read loop, setting the field separator IFS to = so that we can split the name and value from each string. By setting the line delimiter ( -d ) to an empty string, we cause read to use the null character (the "first" character of a null-terminated string) to split lines. Then, just unset each name in turn (taking care to quote it).

Источник

Guide to Remove Environment Variables in Linux

This guide begins with easy instructions to remove environment variables in Linux for both users looking for a fast solution and users looking for understanding of Linux environment variables.

After reading this tutorial, you will be able to delete Linux environment variables by running a simple command and to modify and add environment variables.

This article also includes an explanation of environment variables for users who are not familiar with them. All steps described in this content contain screenshots, making it easy to understand. It is recommended for readers to apply the described examples to get used to interacting with variables.

The unset command to remove environment variables in Linux

This document begins describing the necessary steps. Below this section you will find a full guide on environment variables to understand what they are and how to deal with them.

The command to remove environment variables in Linux is unset, which is executed followed by the variable you want to remove. The syntax is: unset

Before removing a variable, let’s list them using the printenv or env commands.

If I want to remove the LANGUAGE variable I run the following command, as shown in the figure below:

Then, I run env or printenv (both return the same output) to check if the variable was deleted.

Читайте также:  Восстановление файлов linux раздела

As you can see, the environment variable was successfully removed.

If you want to add the variable again, use the export command as shown below:

After adding the variable using the set command, you need to logout and login again to see the changes. As you can see in the screenshot below, the variable was added.

That’s about removing environment variables in Linux, just use the following syntax as shown previously.

If you are not familiar with environment variables, I recommend you keep reading this tutorial.

What is an environment variable in Linux

Environment variables can be seen as references for the bash shell, or processes interacting with shells.

For example, when the hypothetical user named linuxhint is logged in the system. The $HOME variable which specifies the user home is /home/linuxhint. Another example would be the $USER variable which specifies the user is linuxhint.

For example, a bash script to be distributed between different users uses the $HOME variable to learn the home directory of the user running the script. If the linuxhint user runs the script through the $HOME variable, the script will know the user home is /home/linuxhint. If the user torvalds executes the same script, his $HOME variable will refer the script to /home/torvalds as home directory.

If instructed, bash scripts will fetch information from the executing user environment variables to behave accordingly.

To see our environment variables, you can run the env or printenv commands as shown below.

The environment variables shown in the above figure contain useful information for shell sessions.

The following list shows some of the most popular environment variables:

  • SHELL: This variable specifies the shell type and its path. In the example above the defined shell is bash.
  • HOME: The $HOME variable refers to the user’s home directory.
  • LANG: This variable defines the locale.
  • PWD: The $PWD environment variable shows the current working directory.
  • LOGNAME: This variable refers to the user who started the session.
  • DESKTOP_SESSION: This variable shows your X Window manager, in my case as you can see in the previous screenshot, my desktop environment is MATE.
  • USER: Refers to the currently logged in user.
  • PATH: The $PATH variable refers to all directories containing binaries the user can execute.

Modifying an environment variable:

The $PATH environment variable specifies the user binary (executable) file directories. A close view on this variable shows the following directories containing binaries the user can execute. When the user runs a command or calls a program, the shell will search within the defined directories in the PATH variable for the executable binary. If the binary is within a directory which is not included in the PATH variable, the user won’t be able to run it.

What you see below in the PATH variable is a list of directories containing executable binaries, separated by two dots:

To see a specific variable, you can use the echo command followed by the variable. It is preceded by a $ symbol, as shown in the image below, in which only the $PATH variable is printed.

The command below will return a more user-friendly view.

Now, let’s assume you have an executable file within a directory which is not defined in your $PATH variable and you want to add it.

In the example below, the binary is in the hypothetical directory /custom (Under the root directory) which is not defined in the $PATH variable.

Читайте также:  Полезные приложения linux ubuntu

To add it, use the following syntax, where /custom is the new directory.

See the environment variable to check if the new value was added by running the command below.

As you can see, it was successfully added. Now, the user can run binaries within the /custom directory.

Let’s assume we want to remove the /custom directory we added while leaving the rest. For this you can execute the command below.

Check the PATH variable again to confirm the custom directory was deleted as shown in the following figure:

If the path we want to remove has more than a directory, for example /home/usr/bin, the previous command would be as shown in the example below.

Adding new environment variables

In previous sections it was explained how to remove (unset) and modify environment variables. This section explains how to add them, for example, to hold a reference for a script.

The process is simple, we only need to run the export command followed by the variable and its value.

Logout and login back in the terminal. Then, print the environment variables by running env or printenv and you will see the new variable.

Note: To permanently add an environment variable, add the export line in the .bashrc file.

Local vs user vs system wide environment variables

  • Local environment variables: Local environment variables belong to the current session and may disappear after the session is closed.
  • User environment variables: User environment variables are defined in user’s configuration files. They are always loaded from the home directory when the user logins.
  • System wide variables: This type of variables don’t belong to a specific session or user, but to the entire system. For example, they can be general variables which affect all users.

To edit user environment variables you need to edit the .bashrc file located in the home directory. Variables exported to this file will load every time the user starts a session.

System variables are stored in the /etc/bash.bashrc file, that’s the file you need to edit to define general variables for all users.

Removing duplicate values in environment variables

In some cases, users by mistake duplicate environment variables values. This is not a real problem, but printing variables becomes messy.

In such a case the following line using the PATH variable as example, should remove duplicated entries.

Now, let’s see the different types.

Conclusion

As you can see, environment variables are a vital part of the operating system. Without environment variables we could not even execute a binary or be linked to a home directory. Understanding how environment variables work is pretty simple and a must for every Linux user. Variables are not only relevant for Linux operating systems but also to Unix, Mac OS, and Windows.

This tutorial was focused on the most widely used shell, bash, other shells like zsh have different ways to manage variables.

Thank you for reading this tutorial explaining how to remove environment variables in Linux and how to interact with them. Keep reading Linux Hint for more professional Linux tutorials.

About the author

David Adams

David Adams is a System Admin and writer that is focused on open source technologies, security software, and computer systems.

Источник

Оцените статью
Adblock
detector