1. Overview
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.
2. Using the unset Command
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.
3. Assigning the Empty Value
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.
4. Using the env Command
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
5. Conclusion
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.