
Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
Variables are the building blocks of any programming language, and the Linux shell isn’t an exception. As a programmer, we often deal with variables. One of the common operations in shell programming is to clear the value of exported variables.
In this tutorial, we’ll discuss the various ways to achieve this.
The unset command is a shell built-in that can be used to clear the value of an exported variable. Let’s use this command and verify the result:
$ export file_name="test.txt"
$ env | grep file_name
file_name=test.txt
$ unset file_name
$ env | grep file_name
In this case, we’re using the env command to verify the variable has been cleared from our shell environment.
We can clear the value of an exported variable by assigning it an empty value:
$ export file_name="test.txt"
$ env | grep file_name
file_name=test.txt
$ export file_name=
$ env | grep file_name
file_name=
Note that this method doesn’t remove the variable from the environment – it merely assigns an empty string value to it.
The env command runs a program in the modified environment. We can use this command to clear the value of an exported variable:
$ export file_name="test.txt"
$ env | grep file_name
file_name=test.txt
$ env -i bash
$ env | grep file_name
Here, we’re using the -i flag, which clears the variables exported by the user and starts a new session of Bash with default values.
Let’s exit from the new Bash session and verify that the variable is present in the older session:
$ exit
$ env | grep file_name
file_name=test.txt
In this tutorial, we discussed various examples to clear the value of an exported environment variable. We can use these commands in our shell scripts to make them more robust.