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:

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:


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:

$ help unset
$ help declare
$ man bash

Posted by: SXI ADMIN

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.


How to KVM, QEMU start or stop virtual machine from command line (CLI)

KVM or Kernel Based Virtual Machine is a popular virtualization technology. It allows you to run virtual guest machines over a host machine. To start...

How to Docker backup Saving and restoring your volumes

Running a Docker volume backup First, we spin up a temporary container, and we mount the backup folder and the target Docker volume to this container....

How to Start and Enable Firewalld on CentOS 7

In this article, we discuss how to start and enable firewalld. It is highly recommended that you have a firewall protecting your server.Pre-Flight CheckThese...