How to undefine and unset a bash environment variable on Linux or Unix

Posted on in Categories , , , , last updated March 8, 2016

I have set the shell variable. I no longer need the variable. How do I undefine or unset a variable in bash on a Linux or Unix-like desktop system?

Creating and setting variables within a script (or shell prompt) is fairly simple. The syntax is:

varName=someValue
export varName
export vech="Bus"
echo "$vech"

How do I unset a variable in bash?

Use unset command to delete the variables during program execution. It can remove both functions and shell variables. The syntax is:

unset varName

To unset the $vech, enter:

unset vech

Verify it:

echo $vech

A note about readonly variables

Please note that some variables cannot be unset if they are defined as readonly by the system or sysadmin:

unset BACKUPDIR

Sample outputs:

-bash: unset: BACKUPDIR: cannot unset: readonly variable

You can define your readonly variables using the following syntax:

declare -r BACKUPDIR="foo"

How do I unset a shell function on bash?

The syntax is as follows to treat each varName as a shell function:

unset -f varName
unset -f tarhelper

For more info, type:
bash-unset-command
$ help unset
$ help declare
$ man bash

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

3 comment

Comments are closed.