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

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:

ADVERTISEMENTS

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

🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
3 comments… add one
  • Nan Xiao Jan 7, 2016 @ 5:09

    How is the picture(“How to I unset a variable in Bash?”) created? Which tool do you use?

  • ramji Jan 29, 2016 @ 8:45

    for i in { 1..7 }
    do
    echo “welcome $i”
    done
    does not work well….what can i do???

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.